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") ) ) );
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().
Related
I am reading content of GET query string, and every time I encounter & for ecample Blackstone Woodfire & Grill, GET is reading Blackstone Woodfire.
How can I avoid this, if possible?
I know I could encode the special characters from the reference page, then decode them when are directed to this page.
I'm just curious.
The problem is that the parameters you send using get, are separated using a &.
So if you have an url like
http:/example.com?param_1=value_1¶m_2=value_2
You will have an $_GET array like
array(
param_1 => 'value_1',
param_2 => 'value_2'
);
Now if you send and url like:
http://example.com?param_1=value_1 & value_2
You will have an $_GET array like
array(
param_1 => 'value_1 ',
' value_2' => ''
);
Simply becuase that is the way sending GET params works.
On the recieving side, there is not much you can do, the problem lies at the other end.
The GET parameters that are beeing send must indeed be encoded, within PHP that is done using
echo 'http://example.com?param_1=' . urlencode('value_1 & value_2');
Javascript uses encodeURIComponent() to solve this issue.
PHP calles urldecode() automaticly on every get parameter when it is creating your $_GET global.
You could use urlencode to encode the get string. And later if u want to fetch it from $_GET u urldecode.
You could replace all ampersands to %26
I have a little static function so that I can easily build html valid urls on my local website, it is below;
public static function url($path = false) {
// Build return url with special html characters escaped
return 'http://127.0.0.1/' . htmlspecialchars($path);
}
I have two urls one inside an anchor and another is inside a form action, they are below;
Root::url('test?category=' . $category . '&index=' . $index) // Href
Root::url('test?category=' . $_GET['category'] . '&index=' . $_GET['index']) // Form
GET === $, you can see inside my static function that I use htmlspecialchars to escape special html characters from my url.
The anchor one returns a valid link and works as expected. The form one however returns the following, as in when I click on the form submit, my url in my browser is as follows.
http://127.0.0.1/test?category=innate&index=0
Why is this? My website breaks because it is dependant on the GET parameters being valid.
Thanks for your time, hope this made sense.
EDIT
I insert the return value of the function call straight into my form action,
<form
action="<?= Root::url('test?category=' . $_GET['category'] . '&index=' . $_GET['index']); ?>"
method="post">
EDIT
The form html is as follows;
<form action="http://example.com/test?category=innate&index=0" method="post">
The anchor html is as follows
<a href="http://example.com/test?category=innate&index=0">
Could it be something to do with the server sending a POST request even though I have GET parameters?
EDIT #3
Ok so it has something to do with my function or what I am passing in, I hard typed in the url in the form submit and it worked, no problems, which means it can only be what my function is returning.
I myself cannot see what I may be!
ANSWER
After the form was being submitted, I was redirecting to the same page using header to counter form resubmission. The string for the header was being generated by Root::url().
Two hours this took me to figure out, but boy does it feel good!
Normally you wouldn't add a query string to a POST URL. It's not forbidden, though, it may only be somewhat confusing, especially if you use $_REQUEST (which you don't, it seems).
I don't know why your browser shows an uninterpreted &, it should interpret it.
Your problems are likely due to one of these:
a bad browser - try another one
bad content of the form input fields
other
This is quite logic.
I assume your url() method looks like this:
url($string){
echo htmlspecialchars($string);
}
Let's have a look at the $string you are passing:
'test?category=' . $_GET['category'] . '&index=' . $_GET['index'];
As I see in your output, replacing the values, the final string before htmlspecialchars() occur would be:
'test?category=innate&index=0' and after it: test?category=innate&index=0
What happened here? you first concatenated the string, and then htmlspecialchars()'ed the & used to separate the parameters. And to not break the url, you don't want to convert THAT '&'.
Also to sanitize the url you shouldn't use htmlspecialchars() because most html entities would convert to somthing like & + somename + ; for example the Euro symbol would convert to € and you don't want the actual & symbol in your url, the browsers will interpret it as you have another new parameter awaiting.
You should use urlencode(), which will convert your & into: %26 , also, the function's name is self-explanatory, it's encoding a string to use on a URL.
Still, you want the & to separate the parameters, but not in the $GET values. What should we do? to urlencode the values before concatenating the string. I would suggest a method like this one:
function url($page, $get){
$parameters = array();
foreach($get as $k => $v) $parameters[] = urlencode($k)."=".urlencode($v);
//We are concatenating with ? and & the urlencoded() values in the next line:
echo urlencode($page).'?'.implode('&', $parameters);
}
url('test', $_GET); // outputs: test?category=innate&index=0
This would get rid of the special chars from a form's field names and values.
I noticed you will use 2 fixed parameters, category and index, so the method could be like this:
function url($page, $get){
$page = urlencode($page);
$category = urlencode($get['category']);
$index = urlencode($get['index']);
echo "$page?category=$category&index=$index";
}
Hope this is what you needed
When I grab the title from my Word Press posts in code and pass them around as email, the punctuation gets a bit mangled.
For example "TAMAGOTCHI P’S LOVE & MELODY SET" comes out as "TAMAGOTCHI P’S LOVE & MELODY SET".
Any ideas how I prevent this?
Let me know if you need to see the specific code I'm currently using. (I'm not really sure if this is a WordPress issue, or a PHP issue.
EDIT
What happens is that this title is passed to a form via the query string. Then when the form is submitted, I take the string from the form field and email it.
So I guess I need to decode the html either before I pass it into the form field, or else before I email it.
EDIT 2
Weird, so I looked closer at the code and I'm already doing a urldecode before I pass the value into the form field
jQuery('#product_name').val("<?php echo urldecode(strip_tags($_GET['pname'])); ?>
Is there some default encoding happening when you serialize (for ajax formhandler)
var dataString = $(this).serialize();
EDIT 3
OK turns out the code is more complex. Title is also passed to some kind of wordpress session before it's hits the form. I'll figure it out where exactly I need to put urldecode. Thanks!
This is one WordPress "feature" I could do without.
Here's one down-n-dirty method to get the fancy quotes (or other entities) replaced:
$title = get_the_title( get_the_ID() );
$title = str_replace( '’', "'", $title );
echo $title;
We could integrate deeper, by hooking into the_title, if you want this same de-entities functionality throughout the site. This code block would belong in your theme's functions.php file.
function reform_title($title, $id) {
$title = str_replace( '’', "'", $title );
return $title;
}
add_filter('the_title', 'reform_title', 10, 2);
Im not really sure about wordpress, but the issue itself its that the text its coming out as URLENCODE instead of a UTF-8 or other encode.
You have two options
When you receive the text you never turn it back to normal encoding (Which is weird as usually is de-encoded by php when you access the $_GET or $_POST variables)
You are parsing the message with the urlencode() function.
I am using PHP to save the values of a form as JSON into a cookie like so:
// set cookie with search values so we can use jQuery to repopulate the form
setcookie('jobSearchValues', json_encode($form_state['values']), 0, '/');
This works great and then on the JavaScript side I can use this to get at the values:
var jobSearchValues = JSON.parse($.cookie("jobSearchValues"));
$("#keywords").val(jobSearchValues.keywords);
Again this works great, but the problem is that when a value for one of the fields in the form has a space in it, the space gets replaced with a "+". So when the form gets repopulated the text field displays like this for example "hi+mom". Is there a better way to go about this? By the way, $form_state['values'] is a PHP array. There are 4 fields in the form that I am setting as JSON into the cookie.
Use setrawcookie( '<name>', rawurlencode( json_encode( $value ) ), ... ) and then manually url-decode & json-parse on the client side (with JSON.parse(decodeURIComponent(cookie)))
This is weird. json_encode is not supposed to replace spaces with +..
setcookie is probably urlencoding it.
You will have to urldecode it in javascript before using it.
Try this:
(taken from phpjs)
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
and then
var jobSearchValues = JSON.parse($.cookie("jobSearchValues"));
$("#keywords").val(urldecode(jobSearchValues.keywords));
I think I have the need to take a uri which has been decoded in PHP, and re-encode it.
Here is the situation:
JavaScript passes encoded uri as query string parameter to php script.
PHP script embeds uri as a hidden input value in an html document, responds with the document to a user agent.
JavaScript reads embedded uri and sets location of current document based on value of hidden input.
On Step 2, I am finding that the Uri is fully decoded after reading it in via $_GET. So when I embed the uri in the hidden input, it becomes un-encoded. So I would like to run a PHP script which re-encodes the Uri properly ex:
http://my.example.com/dog walk?is=very great
==>
http://my.example.com/dog%20walk?is=very%20great
Is there a pre-built php function for this or should I just write my own?
PLEASE NOTE: urlencode and urldecode are not the answer to get the desired input/output I have in the example above.
Thanks,
Macy
Are you looking for : http://fr.php.net/manual/en/function.urlencode.php ?
I don't know if will help you, but PHP have 3 useful functions:
$url = parse_url('put the url here');
parse_str( $url['query'], $query ); // generating an array by reference (yes, kinda weird)
echo $query; //in this line, you can encode or decode.
or, if you want to mount a query, you can use http_build_query(); that accepts values from an array, like:
$url = 'http://my.example.com/dog walk?';
$array = Array (
'is' => 'very_great',
);
$url_created = $url . http_build_query($array);
urldecode:
http://www.php.net/manual/en/function.urldecode.php