How do I get a fully decoded string - php

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

Related

I want to display encoded url that I pass to this page

I want to print encoded url with the help of echo, for example I send variables like this:
"http://www.indiandeal.in/test.php?go=http://www.facebook.com/indiandeal"
It is working fine if I pass any variable but not with encoded url string. Normal url string works fine.
i don't want to encode the url.
i want this to work
http://www.indiandeal.in/test.php?go=http%3A%2F%2Fwww.facebook.com%2Findiandeal&123=234
this should print the url as
www facebook com indiandeal&123=234
but it displaying only
http www facebook com/indiandeal
Here is my code:
<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = $_GET["go"];
echo $txt1;
?>
</body>
</html>
If you pass an encoded url it will automatically be decoded
Warning
The superglobals $_GET and $_REQUEST are already decoded.
Using urldecode() on an element in $_GET or $_REQUEST could have
unexpected and dangerous results.
If you still want to see it encoded you can use urlencode()
Edit based on your comment.
If you want to save the encoded version of your request variable named go you can do
echo urlencode($_GET['go']); // this encodes it again
//echo urlencode("http://www.facebook.com/indiandeal");
Output
http%3A%2F%2Fwww.facebook.com%2Findiandeal
Try this it will work :
A querystring may contain several key-value pairs. When there is more than one key-value pair, they are typically separated by ampersands (&).
input :
http://www.indiandeal.in/test.php?go=http%3A%2F%2Fwww.facebook.com%2Findiandeal&123=234
Here, $_GET["go"] only gives you the value associated with go.For access the whole query string you have to use this :
The raw, unprocessed query string can be retrieved by the QUERY_STRING server variable:
echo $_SERVER['QUERY_STRING'];

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.

Why doesn't urlencode and urldecode work?

here's the code i'm using:
$from=urldecode($_GET['from']);
$str =urldecode("%2B");
echo "$str<br>";
echo "$from<br>";
and here's part of the URL: from=%2B995594262653
why does this echo
+
995594262653
? (note, there's a space in front of the number).
i am using $str to check if the function works at all. apparently, it works for a simple %2B. What could be an issue?
It is working, but you need to realise that PHP will automatically urldecode the data it in puts in the $_GET array. You are doing it a second time and transforming the input even more.
When your script runs, $_GET['from'] contains +995594262653
When you run that value through urldecode, the + gets transformed to a space.

Passing base64-encoded data in php

I have a page that receive via GET a base64 encoded data, it print data in an input hidden and it pass via get to another page.
The problem is this: when i pass
"Peuq/0X4XhFV+XNa8T06qFrP8lRadORUQBGJ1w6D4m33Jaqx/skKDEJIxjldBrcklboL/uB4C65cjz3BHMPmd3moEJ4GTK5k5Jwf9Ny4BA467bwgeaHJuOS+CjwFlIOzrhSWHTMVl4zWVvwMauuFAjhuMjOOj0/X5L12IcwGTTqLgHo"
via GET it becomes
"Peuq/0X4XhFV XNa8T06qFrP8lRadORUQBGJ1w6D4m33Jaqx/skKDEJIxjldBrcklboL/uB4C65cjz3BHMPmd3moEJ4GTK5k5Jwf9Ny4BA467bwgeaHJuOS CjwFlIOzrhSWHTMVl4zWVvwMauuFAjhuMjOOj0/X5L12IcwGTTqLgHo"
...so openssl can't work. How can I solve it?
Base64 can output + signs which are interpreted as spaces when sent in the URL. You can use urlencode to mitigate this:
<?php
$base64_data = $_GET['base64'];
$url_data = urlencode($base64_data);
$field_data = htmlspecialchars($url_data);
printf('<input type="hidden" value="%s" name="pass-it-on">', $field_data);
?>
On page two:
<?php
$base64_data = $_GET['pass-it-on'];
$real_data = base64_decode($base64_data);
?>
Note that there's no need to decode the htmlspecialchars ur urlencode calls since this is done automatically.
Certain characters in the URL are special, like + which stands for a space. To send arbitrary data via the URL, you need to URL escape it to avoid characters contained in the data being recognized as "special characters". Since you're putting the data into HTML, you also need to HTML-escape it to avoid characters in the URL-encoded data being recognized as special HTML characters. Hence:
$data = /* some data */;
$base64Data = base64_encode($data);
$urlData = urlencode($base64Data);
$htmlData = htmlspecialchars($urlData);
printf('<input type="hidden" value="%s" name="pass-it-on">', $htmlData);

how to decode something that is encoded with encodeUri()

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">

Categories