PHP Get method, escaping the "&" value - php

i have this Download link that will be using a GET method, here's my code:
echo "<a href='dlexcel.php?pname=".s1."&year=".s2."'>DOWNLOAD</a>";
that will be recieve by dlexcel.php
$_GET['pname'].$_GET['year'];
the problem is, s1 is string that can contain the a value &. and the string itself is not complete when $_GET is called.
i already used str_replace and preg_replace but i dont know how to. i need to pull the & out and replace it with something else, i just dont know how or what.

You need to use
urlencode($s1)
when encoding a string to be used in a query part of a URL

Try http_build_query(). http://www.php.net/http_build_query
echo '<a href="dlexcel.php?', http_build_query(array(
'pname' => $s1,
'year' => $s2
), '">DOWNLOAD</a>');
This takes care of encoding data, while building the entire query string from an array for you, meaning you aren't manually hacking it together. Remember, there is more than just & that you must encode.

Related

PHP: rawurldecode() not showing plus sign

I have a URL like this:
abc.com/my+string
When I get the parameter, it obviously it replaces the + with a space, so I get my string
I replaced the + in the url with %2B, then I use rawurldecode(), but the result is the same. Tried with urldecode() but I still can't get the plus sign in my variable, it's always an empty space.
Am I missing something, how do I get exactly my+string in PHP from the url abc.com/my%2Bstring ?
Thank you
In general, you don’t need to URL-decode GET parameter values manually, since PHP already does that for you, automatically. abc.com?var=my%2Bstring -> $_GET['var'] will contain my+string
The problem here was that URL rewriting was in play. As http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_b explains,
mod_rewrite has to unescape URLs before mapping them, so backreferences will be unescaped at the time they are applied.
So mod_rewrite has decoded my%2Bstring to my+string, and when you rewrite this as a query string parameter, you effectively get ?var=my+string. And when PHP applies automatic URL decoding on that value, the + will become a simple space.
The [B] flag exists to make mod_rewrite re-encode the value again.
Like this:
echo urldecode("abc.com/my%2Bstring"); // => abc.com/my+string
echo PHP_EOL;
echo rawurldecode("abc.com/my%2Bstring"); // => abc.com/my+string
Further if you want to get the actual my+string, you can utilize the powers of parse_url function which comes with PHP itself, although you have to provide a full URL into it.
Other way is just to explode the value by a / and get it like this:
$parts = explode('/', 'abc.com/my+string'); // => Array(2)
echo $parts[1] ?? 'not found'; // => string|not found
Also read the documentation on both: urldecode and rawurldecode.
Example here.

Why is the string length showing up in the URL?

I am trying to pass an array through a url. I have tried encoding the URL, serializing the URL, serializing and encoding the URL, and no matter what I do, the length of the strings is coming up in the url.
For example, if I pass the array through a URL this way:
<a href='http://splitsum.com/samples/your_store/checkout_form2.php?arr=<?PHP echo serialize($order); ?>'>Next Page</a>
The resulting URL looks like this (with the string count printed out):
.....s:15:%22shipping_method%22;s:20:%22Flat%20Rate%20(Best%20Way)%22;.....
Does anyone know why this is happening? I can var_dump the entire array (and see the string counts on the page) but I cant seem to print individual values in the array. Could it have something to do with a problem in the URL and the printing of the string length?
Thanks!
Because you're using serialize(). You should be using urlencode() instead.
serialize is intended to take internal arbitrary data structures, and encode them into a portable format for re-use in a PHP system somewhere else. It does NOT produce code that is guaranteed valid in a URL context. Basically you're using a hammer to pound in a screw. Use a screwdriver instead.
Note that urlencode will not accept an array. Perhaps http_build_query() would be more appropriate
The length is appearing because you're using serialize. That how it outputs. It's used to store a PHP variable, so that it can be loaded back into PHP again. It's output format contains the length of arrays/strings.
This is the wrong tool for this job. You want to use http_build_query here instead.
<a href='http://splitsum.com/samples/your_store/checkout_form2.php?<?PHP echo http_build_query(array('arr' => $order)); ?>'>Next Page</a>
Then $_GET['arr'] in checkout_form2.php will be your $order array.

PHP http_build_query special symbols

I want to create an url out of an array with the help of http_build_query (PHP). This is the Array:
$a = array("skip" => 1, "limit" => 1, "startkey" => '["naturalProduct","Apple"]')
After calling
$s = http_build_query($a);
I get the following string $s:
skip=1&limit=1&startkey=%5B%22naturalProduct%22%2C%22Apple%22%5D
My problem is, that I would need an url like this:
skip=1&limit=1&startkey=["naturalProduct","Apple"]
which means, that I don't want to convert the following symbols: ",[]
I have written a conversion function which I call after the http_build_query:
str_replace(array("%5B", "%22", "%5D", "%2C"), array('[', '"', ']', ','), $uri);
My question now: Is there a better way to reach the expected results?
My question now: Is there a better way to reach the expected results?
Yes, there is something better. http_build_query­Docs by default uses an URL encoding as outlined in RFC 1738. You just want to de-urlencode the string. For that there is a function that does this in your case: urldecode­Docs:
$s = http_build_query($a);
echo urldecode($s);
I hope you are aware that your URL then is no longer a valid URL after you've done that. You already decoded it.
You don't need to decode the special characters - they are automatically decoded when PHP's $_GET superglobal is generated. When I do print_r($_GET) with your generated string, I get this:
Array ( [skip] => 1 [limit] => 1 [startkey] => [\"naturalProduct\",\"Apple\"] )
Which has decoded every character, but hasn't unescaped the double quotes. To unescape them, use stripslashes():
echo stripslashes($_GET['startkey']);
This gives
["naturalProduct","Apple"]
Which you can then parse or use however you wish. A better solution, as ThiefMaster mentions in the comments, is to disabled magic_quotes_gpc in your php.ini; it's deprecated and scheduled for removal completely in PHP6.

Need to run GET type operations on a string. Regex?

am working on some API stuff. I can pass some GET data "opt" to an application and on save in the application, the data "opt" is returned in POST. All good.
I need to pass more data to this api and I want to secure it slightly, so I have built a string containing several parts and encoded into base64.
unencoded string would look like this sec_key=xxxxx&url=../dffd/dfg/dfg.jpg&key=xxxxxx
if needed I can easily change that to:
sec_key=xxxxx&url=../dffd/dfg/dfg.jpg&key=xxxxxx
on save in the API app, I receive my encoded string back, then decode - all good.
Question is, I would usually use $_GET to strip out each data part. Can I use $_GET in some way to read from a $string rather than the url?
or do I need some regex and preg_match?. If so, whats the regex to mimic $_GET data extraction..
If you want to extract some data from a string that contains something that looks like a query string, you'll want to take a look at parse_str().
For example, the following portion of code :
$string = 'sec_key=xxxxx&url=../dffd/dfg/dfg.jpg&key=xxxxxx';
parse_str($string, $data);
var_dump($data);
Would get you :
array
'sec_key' => string 'xxxxx' (length=5)
'url' => string '../dffd/dfg/dfg.jpg' (length=19)
'key' => string 'xxxxxx' (length=6)
If needed, you could also use $_GET instead of $data, when calling parse_str().
It doesn't look like quite a good practice... But it'll work.

PHP - How to pass a long unescaped string from one page to another?

I would like to pass a long string to a second page.
Normally I pass short strings as variables
www.example.php?var=something&var2=somethingelse
In this case tho I would like to pass a long sentence to a second page and not have to replace all the white spaces with dashes deal with commas and apostrophes.
Is there a simple way to do this that Im missing?
Do I have to re-query the database?
Thanks
There is no problem in passing long values, that's what the urlencode() function is for:
$link = 'www.example.com?longValue=' . urlencode($arbitraryLengthString);
And you don't need to decode it manually, that's done automatically by PHP. But if it's a really long value that you intend to use on many pages, it might be better to put it into a session.
Use urlencode or http_build_query. No need to decode the message then.
base64 is not an encryption, and just about every programmer can spot it and convert it. You should not relay on that as some secure method of sending message from page to page.
If you just want it to be untampered with, you can also send along a hash of the string, with a secret salt for your server.
$salt = 'longsecretconstanttexthere';
$url .= '?' . http_build_query(array('text' => $str, 'hash' => md5($str . $salt));
Reciveing end:
$str = $_GET['text'];
if ($_GET['hash'] !== md5($str . $salt)) {
//not the original string
}
For a secret method, store the text in $_SESSION or db with a key. Send that key to the next page.
base 64 encode it, and then decode again when the other page receives the GET param
$str = "I'm an obnoxious string, meh meh"
$str = base64_encode($str);
** Echo link **
Then on the receiving page
$str = base64_decode($_GET['str']);
Depending on the length of the string in question, you may want to look at the database method, sessions or using POST to send your data instead of GET.
GET has limits and is typically is not meant to pass large amounts of data, you may end up running into situations where your string becomes truncated if it's long enough.
use $_SESSION array

Categories