PHP ajax variable


#1

Good Day,
Pls I need help on php and ajax…Am trying to pass php session variable to ajax for token secure…below is the ajax and php code…

index.php…

$salt = "B94kJ4";
$imgToken = sha1(uniqid(rand(), true).$salt);
$_SESSION['imgToken'] = $imgToken;

ajax code js…

var form_data = {
    tokenVal: "<?php echo $_SESSION['imgToken']; ?>", //used token here.
  is_ajax: 1
};


  $('.crop_image').click(function(event){
     
      $.ajax({
        url:"upload.php",
        type: "POST",
        data:{"token": form_data},
        success:function(data)
        {
$('#uploadimageModal').modal('hide');
        }
      });
  ;

upload.php file…

if ($_POST['token'] == $_SESSION['formToken']) {

//process

}

but when I try to echo the $_POST[‘token’] variable send by ajax I get error.

Notice: Array to string conversion in C:\xampp7\htdocs\vvccccv\upload.php

Pls kindly help on how I can access the $_POST[‘token’] array


#2

What do you get if you do

var_dump($_POST);

at the start of your upload.php file?

I’m going to guess you need to use something like $_POST['token']['tokenVal'] to access the value you want, but my JS knowledge isn’t that good, and my ‘interaction between JS and PHP’ knowledge even less good.


#3

@droopsnoot

When I echo var_dump($_POST); I get the "data:image/png;base64 string and when i echo echo $_POST['token']['tokenVal']; nothing is return or display and when I echo $_POST['tokenVal']; I get Notice: Undefined index: tokenVal in and var_dump($_POST['tokenVal']); return NULL.

The value is not yet pass… $_POST[‘token’]; still return Notice: Array to string conversion in C:\xampp7\htdocs\vvccccv\upload.php


#4

@rpkamp
@TomB

Pls I kinda need help on how I can loop the array I think that is what is needed but not be able to come up with it…


#5

Nope. What you need is to figure out what your data are. With regards to that your observations don’t make sense: you say that $_POST is a string, but it’s always an array (proof of that is that you get an array-to-string notice, not an undefined-index notice, as would be the case if $_POST were a string).

Which is totally not what it should contain to begin with (the expectation would be a hash and a number). There might be an issue with your JS to solve first.


#6

I’m not sure why you’re expecting to see anything but that error with this code.

var form_data = {
    tokenVal: "<?php echo $_SESSION['imgToken']; ?>", //used token here.
  is_ajax: 1
};

form_data is an array (well, javascript object) then you send the array via ajax:

data:{"token": form_data},

$_POST['token'] contains form_data, an array.


#7

This is what I get when I echo var_dump($_POST);

array(2) { [“image”]=> string(129822) "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQVR4nOy9Z5RVZba2DQYwIBhRMTTBhAgGzFm7DW1uW7vVNiEmQETJGFHarIhoGzABiiKoZJAkGYqKO6+cw147V64ChOv7sTbYXxhnvON7z3k5fdo5xj2eVXvXGFVQz1XznnM+a1WHDr/Ff1kAHZcuVTqvSSaPmTjv254HDrvzog7Dbrj8sHF33/xtrGpYRUwaVhERPtlcJ8ytjKmra2I6lXGNrVG9oiJhzq2V7BlVkjmsKmYOq0lYN1em9MsrU/blWwSjZzJpHLPGMA4AOu7tf+dv8Vv8hzFnzpx9Ozx0yyEHPHFzr/0eufUPf/3k9fEL4nUbNokyKxNJHpj+D/YZejsdnvoTnUb

Which I was able to get the image and display it…

What am trying to achieve is that I want to pass Session variable value to the ajax and able to access the value return by ajax


#8

@TomB

I want to pass Session variable value to the ajax and able to access the value return by ajax … pls kindly help out if am not to use array for that…maybe that is where the problem is…


#9

You’re in the wrong PHP script. image is not a parameter you pass to upload.php.


#10

I was able to display the image…everything is working fine it just that am trying to secure the ajax request by adding token Id…well pls if you have any idea or code that I can use to secure ajax request I will appreciate that because that is what am trying to do


#11

That means the JS code you posted in post #1 is totally irrelevant to the problem at hand?


#12

That is the part of the code that is giving me issue…

Okay…what am doing is am using Croppie script to crop images…after everything is fine I want to check session variable with the ajax request… below is the JS


  $('#upload_image').on('change', function(){
    var reader = new FileReader();
    reader.onload = function (event) {
      $image_crop.croppie('bind', {
        url: event.target.result
      }).then(function(){
        console.log('jQuery bind complete');
      });

    }
    reader.readAsDataURL(this.files[0]);
    $('#uploadimageModal').modal('show');
    });



var form_data = {
    tokenVal: "<?php echo $_SESSION['imgToken']; ?>", //used token here.
  is_ajax: 1
};


  $('.crop_image').click(function(event){
      $image_crop.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function(response){
      $.ajax({
        url:"upload.php",
        type: "POST",
        data:{"image": response, "token": form_data},
        success:function(data)
        {
          $('#uploadimageModal').modal('hide');
          $('#uploaded_image').html(data);
          $('.doneCrop').fadeIn(2200);
        }
      });
    })
  });

In upload.php file I want to be able to check like…

if ($_POST['token'] == $_SESSION['formToken']) {

//process

}

#13

Is there a scope issue with the location of the definition of form_data? As I said before, I’ve only played a bit with JS, and I suspect you might get a console error if that was the problem. If you display the value of it inside your click handler function, does it contain what you expect it to contain?


#14

This part is not necessary. AJAX (i.e. XMLHttpRequest) automatically sends the cookies along (and hence the processing PHP script has access to the session data). So it would suffice to check on the server if the hash of the data is what is stored in the session.


#15

The whole point of sending that value is to prevent CSRF attacks if I understand correctly, in which case it is relevant to send it to the server.


#17

Whats te other entry in $_POST? the dump indicates that there are two array items.


#18

@rpkamp

What am trying to do it to prevent CSRF attacks…


#19

really? I was able to access the session variable with the processing PHP script… when I echo $_SESSION['imgToken']; the value of the session display…

when I try


var tokenVal = "<?php echo $_SESSION['imgToken']; ?>";

  $('.crop_image').click(function(event){
      $image_crop.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function(response){
      $.ajax({
        url:"upload.php",
        type: "POST",
        data:{"image": response, "token": tokenVal},
        success:function(data)
        {
          $('#uploadimageModal').modal('hide');
          $('#uploaded_image').html(data);
          $('.doneCrop').fadeIn(2200);
        }
      });
    })
  });

and echo $_POST['token']; noting is display…

when I echo var_dump($_POST['token']); I get string(36) display

Can I do something like this to check for the session variable

if (isset($_SESSION['imgToken'])) {
	
//process

}
else {

//bad request

}

but I will like to have something like dis

if ($_POST['token'] == $_SESSION['imgToken']) {

//process

}

any idea or code will be welcome to secure the ajax and prevent CSRF attacks


#20

As you have the ‘raw’ flag set, it is unlikely that the token will display in the browser as it is in raw binary format.