开发者

PHP - post data ends when '&' is in data

开发者 https://www.devze.com 2022-12-26 14:15 出处:网络
I\'m posting data using jquery/ajax and PHP at the backend. Problem being, when I input something like \'Jack & Jill went up the hill\' I\'m only receiving \'Jack\' when it gets to the backend.

I'm posting data using jquery/ajax and PHP at the backend. Problem being, when I input something like 'Jack & Jill went up the hill' I'm only receiving 'Jack' when it gets to the backend.

I have thrown an error at the frontend before that data is sent which alerts 'Jack & Jill went up the hill'.

When I put die(print_r($_POST)); at the very top of my index page I'm only getting [key] => Jack

How can I be losing the data?

I thought It may have been my filter;

<?php

function filter( $data ) {
    $data = trim( htmlentities( strip_tags( mb_convert_encoding( $data, 'HTML-ENTITIES', "UTF-8"开发者_如何学Go) ) ) ); 
    if ( get_magic_quotes_gpc() ) { 
        $data = stripslashes( $data ); 
    } 
    //$data = mysql_real_escape_string( $data ); 
    return $data;
}

echo "<xmp>" . filter("you & me") . "</xmp>";

?>

but that returns fine in the test above you & me which is in place after I added die(print_r($_POST));.

Can anyone think of how and why this is happening?

Any help much appreciated.


You are most likely failing to URL encode the data. The & character separates key-value pairs in submitted form data.

Use encodeURIComponent for this


POST data is sent via the HTTP header in form that is just like the GET data in the url. For example, the data could look like var1=value1&var2=value2&var3=value3. As you can imagine, if the data contains ampersands itself, it's not going to work too well on that format. To be precise, the problem is in how you are submitting the data.

To use ampersands in the post data (or in urls, for that matter) they must be "urlencoded", which means that you must use %26 for the & character. So, it's not really your PHP that has the problem, but whatever is sending the data. It's not encoding the values properly.


Use either encode() or escape() at the javascript end


In the Javascript end you should use escape().

In the PHP end the function is named urlencode().

0

精彩评论

暂无评论...
验证码 换一张
取 消