Encoded JQuery Url not decoding correctly in PHP - php

I am using .ajax() to send a request to the server. The server is using PHP to process the request.
According to php urldecode, $_REQUEST is already decoded and Plus symbols ('+') are decoded to a space character.
What I have found is that Plus symbols are being decoded to a underscore ('_'). This is true for both + and %20. Is there any way around this? This seems like unexpected behavior.
Code sample for what its worth:
ajax:
$.ajax({
url: 'mySite.php',
method: 'POST',
data: $(this).serialize()
});
php:
$myVar = "Veh #";
if (isset($_REQUEST["$myVar"])){
//do stuff
}
//to see request
var_dump($_REQUEST);
The var_dump gives
array(1) {["Veh_#"]=> string(1) "6"}
I would expect is to be
array(1) {["Veh #"]=> string(1) "6"}
fiddler data posted:
Veh+%23=6

I may be incorrect as I'm still learning PHP, but I think this is standard behaviour when using GET and POST in PHP.
see here in the documentation
http://www.php.net/manual/en/language.variables.external.php
I not aware of anyway around this.
also see this stack overflow question
Get PHP to stop replacing '.' characters in $_GET or $_POST arrays?

Note:
Dots and spaces in variable names are converted to underscores.
(php.net - external variables)

Related

Proper way to extract url parameters from an htmlentities() encoded url?

I have this php file resizeImage.php which can be called like this -
http://<domain>/fam/resizeImage.php?&srcImg=<url encoded URL of a remote image>&width=<width>&height=<height>
However, a different module calls the htmlentities encoded version of this URL, in this way -
htmlentities(http://<domain>/fam/resizeImage.php?srcImg=<url encoded url>&width=<width>&height=<height>)
So, following is a sample URL that is called -
http://<domain>/fam/resizeImage.php?srcImg=https%3A%2F%2Flh3.googleusercontent.com%2FVRY0O_3L8VH2wxJSTiKPr72PeM5uhPPFEsHzzYdxenddpTI150M0TYpljnZisQaROR0%3Dh256-rw&width=640&height=960
Now, the request is received by resizeImage.php, but I am unable to get the parameter width using $_REQUEST['width'], but I can do the following -
get htmlentities_decode($_SERVER['REQUEST_URI'])
explode it using & to get the parameter-value pairs.
explode using = to get values against parameters.
So, two things -
I was wondering if this is the proper way to extract the parameters in this scenario.
I do not know the reason why the calling module calls the htmlentities encoded URL. Could there be a better way to suggest them?
You can use PHP's internal functions to parse and decode URLs:
parse_url - parse URL and get the needed components
html_entity_decode - decode html entities
url_decode - decode URL encoded characters
and finally parse_str - to parse parameter string into an associative array
So here's an example code what I'm come up with (you can try it out here):
$parsed = parse_url($url);
parse_str(urldecode(html_entity_decode($parsed['query'], ENT_HTML401)), $tmp);
var_dump($tmp);
...which renders your URL parameters into an associative array:
array(3) {
["srcImg"]=>
string(109) "https://lh3.googleusercontent.com/VRY0O_3L8VH2wxJSTiKPr72PeM5uhPPFEsHzzYdxenddpTI150M0TYpljnZisQaROR0=h256-rw"
["width"]=>
string(3) "640"
["height"]=>
string(3) "960"
}
As for the second part, I think the second module's approach is a little bit safer, since you're placing an URL in an URL's parameter. If you don't want to hassle with parsing and stripping unnessesary parts from the parameter, then encoding the whole is a simple and safe way to keep your URL's out of syntax errors.
In some cases, when people send html code in get parameters htmlentities on single parameters might be ok when it comes to the label, but not for the link itself - they should use urlencode for that:
<a href="htpp://yourdomain.tld/?param1=<?php echo urlencode('<somehtmltag>'); ?>>htpp://yourdomain.tld/?param1=<?php echo htmlentities('<somehtmltag>'); ?></a>

JSON.parse: unexpected character - what character am I missing?

Environment: PHP 5.3.5 MySQL Server 5.5.8, jquery version 1.6
Using Ajax to auto-populate a dropdown list of countries.
I keep getting this error and I have tried numerous things. Such as surround the $results with "'$results'" before encoding. The error still persists.
Here is the an example of output:
array(1) {
[0]=>
array(4) {
["id"]=>
string(2) "45"
[0]=>
string(2) "45"
["nicename"]=>
string(16) "Christmas Island"
[1]=>
string(16) "Christmas Island"
}
}
Here is the ajax (I even tried to change success to complete - the error code is just duplicated if I do that.
$.ajax({
type: "POST",
url: "models/ajaxHandler.php",
data: {handler:"getCountries", nli:"-1"},
dataType: "json",
success: function(results){
//results = $.parseJSON(results);
var resultStr = "";
for(var x in results)
resultStr = resultStr + results[x];
alert("RESULT" + resultStr);
//populateDropDown(results);
},
error: function(xhr, status, error){
alert(xhr+ "| ajax failure: could not populate list of countires | " + status + " | error:" + error);
var xhrStr = "";
for(var x in xhr)
xhrStr = xhrStr + xhr[x];
alert(xhrStr);
}
});
After I encode the json string in php I am escaping for special characters like so:
if (!empty($results)){
$json = json_encode($results);
//$json = form_safe_json($json);
echo $json;
}
function form_safe_json($json) {
$json = empty($json) ? '[]' : $json ;
$search = array('\\',"\n","\r","\f","\t","\b","'") ;
$replace = array('\\\\',"\\n", "\\r","\\f","\\t","\\b", "\'");
$json = str_replace($search,$replace,$json);
return $json;
}
After I encode the json string in php I am escaping for special characters
You don't need to do that -- json_encode() does all the necessary escaping for you, and in fact doing so is probably breaking the valid JSON that json_encode() has produced for you.
[EDIT]
To be clear: PHP's json_encode() function produces valid JSON from any input. (The only thing you need to test for is false if it fails, but even that will parse correctly in jQuery if you echo it, since an empty string is valid JSON).
If your program echos the output of json_encode(), and nothing else, then your program will be serving valid JSON and will not get the JSON parsing error in your JS code.
If your program echos anything else, or if you modify the JSON string before sending it, you may very well get errors.
Things to watch out for:
Don't try to send multiple JSON strings one after the other using multiple calls to json_encode(). This will be invalid JSON. Encode everything you want to send using a single call to json_encode().
Beware of PHP sending unwanted characters (particularly white space and UTF-8 BOM characters) which can cause errors in many situations.
If errors persist, load your JSON URL into the browser direct and view the source. You may see the error straight away. If not, copy and paste the JSON string into one of the JSON test sites on the web and see what it reports. This may help explain the problem.
If you're on PHP 5.4, you can use the PRETTY_PRINT option in json_encode(). This may help you with your debugging.
Perhaps json_encode() could be of some use? http://php.net/manual/en/function.json-encode.php
I am not sure what you try to achieve with the form_safe_json command.
The text string returned from:
$json = json_encode($result);
will contain correctly formated json and should not be further escaped in case you wish for the Javascript to parse it correctly. The escaping made by form_safe_json will break the json.

The & is not allowed for my new password

I have a window on my site where the visitors can change them password.
The problem is that the & character is never taken :
If I put those two new passwords :
stack&
stack& (the second is the confirmation)
The insertion in the BD is stack (without the &).
This is the js code :
data: 'nouveau_mdp=' + $('input#champ_nouveau_mdp').val(),
the alert shwos me "stack&"
In PHP, a var_dump of $_POST gives me :
stack (without the &).
Is & a reserved word for jquery ?
This is my js code :
$.ajax({
type: 'POST',
url: 'modification_mdp.php',
data: 'nouveau_mdp=' + $('input#champ_nouveau_mdp').val(),
dataType: 'text',
success: function(reponse) {
reponse = $.trim(reponse);
Have you an idea to reselove this problem please ?
Thanks in advance.
Encode the field value
data: 'nouveau_mdp=' + encodeURI($('input#champ_nouveau_mdp').val()),
by this way & is encoded with the ascii number.
Try passing an associative array, which jQuery will encode for you:
data: { nouveau_mdp: $('input#champ_nouveau_mdp').val() }
You'll need to change the PHP code that receives this value to match (it gets an array rather than a string).
The ampersand character is not allowed to pass by Get method or by Post method in PHP. As the usual syntax to access the PHP by GET method is ines.php?user=username&password=mypassword,
the '&' character separates the two Variables.
That is why it is does not take '&' from 'Stack&' You may use Javascript to Validate if & is not entered in the text Box. Use JavaScript to encode the varaible... No decoding is required at the PHP end
encodeURIComponent("stack&")
This line is the problem:
data: 'nouveau_mdp=' + $('input#champ_nouveau_mdp').val(),
The & character has a special meaning in HTTP. If you had multiple parameters they would be separated by & e.g. nouveau_mdp=mynewpassword&old_mdp=myoldpassword
What you need to do is encode characters such as &, = etc as their hex equivalents i.e. %26 and %3D respectively.
In JavaScript you can do this with the encodeURI() function.
Though, as mentioned in the other answer, jQuery also allows you to pass a JSON dictionary of parameters, and it will do the encoding for you.

Remove double-quotes from a json_encoded string on the keys

I have a json_encoded array which is fine.
I need to strip the double-quotes on all of the keys of the json string on returning it from a function call.
How would I go about doing this and returning it successfully?
Thanks!
I do apologise, here is a snippet of the json code:
{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}
Just to add a little more info:
I will be retrieving the JSON via an AJAX request, so if it would be easier, I am open to ideas in how to do this on the javascript side.
EDITED as per anubhava's comment
$str = '{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}';
$str = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $str);
echo $str;
This certainly works for the above string, although there maybe some edge cases that I haven't thought of for which this will not work. Whether this will suit your purposes depends on how static the format of the string and the elements/values it contains will be.
TL;DR: Missing quotes is how Chrome shows it is a JSON object instead of a string. Ensure that you have Header('Content-Type: application/json; charset=UTF8'); in PHP's AJAX response to solve the real problem.
DETAILS:
A common reason for wanting to solve this problem is due to finding this difference while debugging the processing of returned AJAX data.
In my case I saw the difference using Chrome's debugging tools. When connected to the legacy system, upon success, Chrome showed that there were no quotes shown around keys in the response according to the debugger. This allowed the object to be immediately treated as an object without using a JSON.parse() call. Debugging my new AJAX destination, there were quotes shown in the response and variable was a string and not an object.
I finally realized the true issue when I tested the AJAX response externally saw the legacy system actually DID have quotes around the keys. This was not what the Chrome dev tools showed.
The only difference was that on the legacy system there was a header specifying the content type. I added this to the new (WordPress) system and the calls were now fully compatible with the original script and the success function could handle the response as an object without any parsing required. Now I can switch between the legacy and new system without any changes except the destination URL.

How to escape "&" ampersand character in form input using jQuery

I have a problem with my jQuery script that send data via POST method. The problem is whenever it sends data via Ajax that has an "&" ampersand in the sentence, it will cut the sentence when found "&".
Please check the images below for more info.
htmlentites
This function is identical to htmlspecialchars() in all ways, except with htmlentites(), all characters which have HTML character entity equivalents are translated into these entities.
If you're wanting to decode instead (the reverse) you can use html_entity_decode().
Example:
echo htmlentities("&"); // &
if your directly doing this in the browser you should be able to use:
encodeURIComponent(string input);
Example:
encodeURIComponent($.trim($("input[name=t-tim_rendered-"+id+"]").val().toString()));
I've been having a huge problem exactly with this situation.
This is just to say that the last answer from Andrew Koester is the perfect answer I was looking for.
In case you are passing multiple form entries from a jQuery form to PHP through the .ajax() call like this:
data: "name=" + name + "&message=" + message + ...
DON'T USE THIS METHOD, it will block the ampersand(&) character from being written by the user on any of the input fields of your form.
Use this one instead as suggested by Andrew:
data: {"name": name, "email": email, "subject": subject, "comments": comments},
This way the user can write any kind of special character whithout worrying a about conflicting with the ajax declaration.
You can use a native javascript escape() function
In line 74
data: : "&task_d=" + escape(task_d) + ""
Alternatively, you could enclose your query string values in quotes
data: : "&task_d='" + task_d + "'"
If you pass your data parameter as a Javascript object, it will convert the characters for you (and IMO make the code look neater). So you should change your $.ajax call to the following:
data: {"user_id": user_id, "time_r": time_r, "task_d": task_d, "p_id": p_id, "df": finished},
You could use 'encodeURIComponent' to accomplish the URL encoding for that component. I used this and validated with browsers IE, Firefox, and Chrome.

Categories