PHP – “&” character gets hidden in $_POST [closed]

Tags: , , , ,

I am using a custom PHP file to send data to my JSON file and update it, but if an ‘&’ character is into a string, that string gets truncated and the text after that ‘&? char gets hidden, as well as the ‘&’.


header('Content-Type: text/html; charset=ISO-8859-1');
$tableName = $_POST['tableName'];

// HTML sanitization
if (strpos($tableName, '<') !== false || strpos($tableName, '>') !== false
){ $tableName = preg_replace("/[^a-zA-Z]/", "", $tableName); }

// Get JSON Table's Data
$data = file_get_contents($tableName. '.json');
$data_array = json_decode($data, true);

$newDataArr = array();

foreach ($data_array[0] as $k=>$v){
    $keysArr = explode("_", $k);
    $kType = $keysArr[0];
    $kName = $keysArr[1];

    echo $_POST[$k]; // This is just to test the output when sending data

Following is the AJAX function I use to get values from an input field (#itemDescription) and call the PHP file above:

var params = 'tableName=Items&description='+ $('#itemDescription').val();

        url : 'm-add-edit.php?',
        type: 'POST',
        data: params,
        async: false,
        success: function(data) {
            console.log(data); // <-- JUST TO TEST THE OUTPUT
        // error
        }, error: function(e) {  

So, if the #itemDescription input contains a ‘&’ character, that gets hidden, and the text after it too.

enter image description here

The console log I get is:

Text with

Is there a way to make ‘&’ character recognizable as any other character and avoid my text to be truncated?


The issue is because you’re sending your data in a URL encoded string where the ampersand character has a special meaning and needs to be encoded.

However, with a POST request you should pass the values in the body of the request, not the URL. The simplest way to do this with jQuery is to provide an object to the data property of the $.ajax settings instead, and jQuery will take care of encoding it correctly and setting it in the right part of the request for you.

In addition, you should remove the async: false setting. Always send AJAX requests asynchronously as synchronous requests are deprecated and will display a warning in the browser console. As you’re using callbacks correctly, you don’t need async: false anyway.

With all that said, try this:

  url: 'm-add-edit.php?',
  type: 'POST',
  data: {
    tableName: 'Items',
    description: $('#itemDescription').val()
  success: function(data) {
  error: function(x, s, e) {
    console.log(x, s, e);

Source: stackoverflow