how to decode something that is encoded with encodeUri() - php

If you encode something using javascript's encodeURI() method, how do yo get the decoded string in PHP?
I have string name= "salman mahmood" which I'm sending via POST message to my server. When I alert() the string at client side it gives me "salman%20mahmood" after encoding.
At server side I'm decoding it using urldecode() but the result I'm getting is "salman". Do I need a different method to decode? the rawurldecode isnt working either; I just need the value with the space restored back.
Edit: thanks every one for the suggestions but im writing the code as follows and it still doesnt work!!
<input type="text" id="chapterNumber" value=<?php echo rawurldecode("chapter%20Two"); ?> disabled="disabled">
it only prints "chapter"

Put it into quotes ' '
<input type="text" id="chapterNumber" value='<?php echo rawurldecode("chapter%20Two"); ?>'disabled="disabled">

Related

How do I get a fully decoded string

I am using $_SERVER['QUERY_STRING'] instead of $_GET to get all my parameters. However, $_SERVER['QUERY_STRING'] encodes the string by itself. Thus, if a user sends an encoded string, it gets encoded again with $_SERVER['QUERY_STRING']. Meaning I have to run urldecode twice.
Encoded string: https://www.example.com/test.php?info1234=3177%3B315961%3B317451%3B315511&info3598=121618%3B136803%3B13830%3B20532
If you use the link above to submit via the URL itself. Meaning you put the parameter in yourself, you get the string (which is what I want):
https://www.example.com/test.php?info1234=3177;315961;317451;315511&info3598=121618;136803;13830;20532
However, if you submit via form, you get a doubly encoded string. So when you decode, it only decodes once, and you have to run urldecode on it again to fully decode it:
https://www.example.com/test.php?info1234=3177%3B315961%3B317451%3B315511&info3598=121618%3B136803%3B13830%3B20532
How can I make sure I get the decoded string (I don't want to run urldecode twice on the string, as it makes my time complexity O(2n). I want to try keep it at O(1) or at the very least O(n). I know using urldecode means n every time.
<?php
$a = urldecode($_SERVER['QUERY_STRING']);
$b = urldecode($a);
if(strpos($a, "%") != false) {
echo "We had to decode twice<br>";
echo $a . "<br><br>Then to:<br>" . $b;
} else {
echo "Only decoded once!!<br>";
echo $a;
}
?>
<form action="test.php" method="get">
myurl: <input type="text" name="myurl"><br>
<input type="submit" value="Submit">
</form>
Method 1:
localhost/test.php?https://www.example.com/test.php?info1234=3177%3B315961%3B317451%3B315511&info3598=121618%3B136803%3B13830%3B20532
This decodes once
Method 2:
Go to localhost/test.php
Submit this link via the form
https://www.example.com/test.php?info1234=3177%3B315961%3B317451%3B315511&info3598=121618%3B136803%3B13830%3B20532
This decodes twice
You will see you get 2 different outputs

Get JSON data stored in a hidden input element?

I'm building a website that store json data to hidden input element with php
<input type='hidden' class='json_data' name='json_data' value='".json_encode($data[0])."'>
with that code, I have this result:
<input class="json_data" type="hidden" value="[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]" name="json_data">
but when I try to get the value with jquery.val and trying to show ALBUM_ID, i get this {
anything wrong with my way of putting json into html correctly?
and then get it with jquery / javascript ?
thanks
First go ahead at this open console and see the result. Ctl+Shift+j.
http://jsfiddle.net/techsin/Q2MHA/
You need to do two things fix. ' and "'
Second just this code
JSON.parse($('.json_data').val())[0]
you need [0] because for some reason your json object is wrapped in []..you would know why.
Your html should look like this
<input ... value='[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]'...>
You need to correctly handle entities in your input's value. If you populate it with PHP, use htmlspechalchars() and use result from this function
inspect the following line carefully.
<input class="json_data" type="hidden" value="[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]" name="json_data">
As you see you have used " for your string enclosement. The json string also includes " which breaks your string enclosement. Use ' to enclose the string.
<input class="json_data" type="hidden" value='[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]' name="json_data">
Try to escape the " with addslashes or htmlspecialchars
or encode the string with base64 and decode it with JS before parsing the string as JSON

JSON string with some html tag failing at parse

I am taking user input sending it to server using jQuery ajax...after inserting user values in database I am sending response back to client as JSON string as following
echo '{"success":"true","data":"'.nl2br($a).'","type":"text"}';
as user input can contain new line, I am using nl2br so that all new line characters are converted to <br> and also know that JSON doesnt support multi line, thats why I am using nl2br....but parsing is failing at client side
pls tell me what the reason and how can I solve it?
parsing code var obj = jQuery.parseJSON(data);
You should be using json_encode, wich will generate a JSON string that contains \r\n for line breaks. Then you will have to replace each \r\n occurences by <br> tags.
echo str_replace('\r\n','<br>', json_encode(array("success"=>"true","data"=>$a,"type"=>"text")));
echo json_encode(array("success"=>"true","data"=>$a,"type"=>"text")
Use the php function json_encode rather then trying to set the encoding yourself. You'll save yourself a lot of trouble that way. http://php.net/manual/en/function.json-encode.php
nl2br() does not replace the line breaks, only inserts <br> before them.
As such, \n is being returned and therefore creating invalid JSON.
You should use json_encode() when creating JSON strings. For simplicity, you could simply use it on data:
echo '{"success":"true","data":' . json_encode(nl2br($a)) . ',"type":"text"}';

JSON array to PHP / MySQL JSON.parse JSON.stringify how to store double quotes and single quotes

I have a form with fields and a text-area that allows any characters to be entered. I can't just submit the form, because the form is being recycled many times over, so the form values are being stored in associative arrays:
<form name='Theform'>
<input type="text" id="VISITOR_DETAILS_NAME" value="Joe">
<input type="text" id="VISITOR_DETAILS_SIZE" value="Large">
<textarea id='VISITOR_DETAILS_INFO'>
User can enter anything here including double " and single ' quotes
</textarea>
<input type="hidden" name="package" id="package" value="" />
</form>
The text-area value are stored in a JavaScript array along with the other form values:
myArray[0]['VISITOR_DETAILS_NAME'] = document.getElementById('VISITOR_DETAILS_NAME').value;
myArray[0]['VISITOR_DETAILS_SIZE'] = document.getElementById('VISITOR_DETAILS_SIZE').value;
myArray[0]['VISITOR_DETAILS_INFO'] = document.getElementById('VISITOR_DETAILS_INFO').value;
I end up with an array something like this:
{
VISITOR_DETAILS_NAME : "Joe",
VISITOR_DETAILS_SIZE : "Large",
VISITOR_DETAILS_INFO : "User can enter anything here including double " and single ' quotes"
};
I then pass this JavaScript array to the hidden form field using JSON.stringify and then POST this to PHP:
document.getElementById('package').value = JSON.stringify(myArray[0]);
Theform.submit();
(For now I'm just posting to an iframe to test that the JSON is passing the JavaScript arrays properly through POST).
When I get it on the PHP side - it seems good to go. It looks like the JSON.stringify has added the backslash to the double quote (\" ) - and now I want to store the values in MySQL. But I want to first test that I can send/reconstruct the JSON back to the javascript as an array - so I try this:
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
I get an ERROR: SyntaxError: Expected token ')' OR SyntaxError: missing ) after argument list
This is strange to me - because when I try it without POSTING - It seems to work fine like this:
document.getElementById('package').value = JSON.stringify(myArray[0]);
now if I try to just pass back the stringified value back to the array
myArray[0] = JSON.parse(document.getElementById('package').value);
- it seems to work fine - no errors
QUESTIONS:
Why am I getting this error when trying to reconstruct the ARRAY from the
POSTED JSON.stringify() value?
Do I save this JSON.stringify() value in MySQL as is?
Or do I PHP json_decode() it first?
I want to grab the form data - handle it properly - store it in MySQL and then read it back into the form when I need it.
Thanks All :)
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
Here you are are trying to convert a JSON text into an HTML representation of a JavaScript string representation of a JSON text, but you aren't doing anything to escape it for either.
If you have any ' characters in the JSON data, then they will terminate the JavaScript string.
If you have any " characters in the JSON data, then they will be represented as \", but \" is a JavaScript string representation of ". Since you don't do anything to escape the text you put in the JS string, the slash character will be consumed by the JavaScript parser and will be gone before it reached the JSON parser.
If you want to convert data for placing in a JavaScript string then you need to escape it.
However, JSON is a subset (almost) of JavaScript. So the process of converting a JSON text to a JavaScript string so it can be parsed into a JavaScript object is over-complicated. You can skip that can just go straight to:
<script>
var foo = <?php echo $json; ?>
</script>
However, since you are taking in the JSON from the client, echoing out directly will expose you to XSS attacks. In order to deal with this you should filter the data on the server.
This will:
Fail to parse any invalid JSON and so not output bad JSON (but it might output nothing, giving you a JSON syntax error, you should apply tests to see if the parse was successful and output a sensible default case if it fails).
Convert any </script> in the data to <\/script> making it safe to place in a script element (because that is how PHP's json_encode works
Such:
<!-- I don't do PHP, this is untested -->
<script>
var foo = <?php
$unsafe_json = $_POST['package'];
$data_structure = json_parse($unsafe_json);
$safe_json = json_encode($data_structure);
echo $safe_json;
?>;
</script>
Do I save this JSON.stringify() value in MySQL as is? Or do I PHP json_decode() it first?
That depends on what you intend to do with the data. In general when putting things into a database it is a good idea to extra the data from the data format and normalize it. That way you can run queries over it.
If you are only going to store the data and then retrieve it, you might be able to get away with not doing that and storing strings of JSON in the database. That loses you a lot of flexibility though and might bite you in the future.

Posting string encoded with htmlentities back to the server

I generate this in a view:
<form method="post">
<input type="hidden"
name="test"
value="<?=htmlentities('<>"&ščé', ENT_QUOTES, 'UTF-8')?>">
<input type="submit>
</form>
Now, should I do this when processing data from the form?
$decodedTest = html_entity_decode($_POST['test'], ENT_QUOTES, 'UTF-8');
I think that this should be allright:
$decodedTest = $_POST['test'];
But I have not found a reference to this.
EDIT: I had printed the posted value of test and I had seen that the value is not encoded. What I don't know is If I can rely on this behaviour and why. I am asking about theory of operation. If I look into the raw post request, I can see that the post data is urlencoded (which is I guess a different type of encoding than htmlentities does). Does that mean that client must perform some recoding before sending the request. Does (client) browser store input values in encoded form or decoded form in memory before sending? (I already know that php automatically decodes urlencoded data in requests so that part is fairly clear to me).
You don't really need a reference because printing htmlspecialchars($_POST['test']) (or just setting Content-Type: text/plain) will immediately reveal that the data inside $_POST is not entity-encoded.
You also don't need to call htmlentities to encode the data in the view -- htmlspecialchars will suffice if your aim is to generate valid markup.
Sending the form, you can do it. Better check

Categories