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_queryDocs 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: urldecodeDocs:
$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.
Related
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.
I am storing an array in string form in a database for later retrieval:
The value of the array happens to be parameters for a filter_val call.
$str = 'array("options" => array("min_range" => 4))';
I know I can use
eval('$options = ' . $str . ';');
to prepare this value for passing to filter_val, but is there any other way to do this?
This related post (while excellent) didn't handle my exact issue.
I would not use eval() to get your string functional. For example, the function eval may be disallowed on some hosts, thus your application will not work.
A more appropriate way would be to store your options in a json_encode()'d string, and decode when you need.
$options = json_decode($options_from_db);
Or as John Conde mentions, you can serialise it.
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.
So I would like to take a string like this,
q=Sugar Beet&qf=vegetables&range=time:[34-40]
and break it up into separate pieces that can be put into an associative array and sent to a Solr Server.
I want it to look like this
['q'] => ['Sugar Beets],
['qf'] => ['vegetables']
After using urlencode I get
q%3DSugar+Beet%26qf%3Dvegetables%26range%3Dtime%3A%5B34-40%5D
Now I was thinking I would make two separate arrays that would use preg_split() and take the information between the & and the = sign or the = and the & sign, but this leaves the problem of the final and first because they do not start with an & or end in an &.
After this, the plan was to take the two array and combine them with array_combine().
So, how could I do a preg_split that addresses the problem of the first and final entry of the string? Is this way of doing it going to be too demanding on the server? Thank you for any help.
PS: I am using Drupal ApacheSolr to do this, which is why I need to split these up. They need to be sent to an object that is going to build q and qf differently for instance.
You don't need a regular expression to parse query strings. PHP already has a built-in function that does exactly this. Use parse_str():
$str = 'q=Sugar Beet&qf=vegetables&range=time:[34-40]';
parse_str($str, $params);
print_r($params);
Produces the output:
Array
(
[q] => Sugar Beet
[qf] => vegetables
[range] => time:[34-40]
)
You could use the parse_url() function/.
also:
parse_str($_SERVER['QUERY_STRING'], $params);
I have two variables from two different SQL queries that I want to put in to one JSON Array (i.e $hometown and $topcat). I am trying to hardcode it but not sure how it's suppose to look.
print(json_encode('{"hometown":"' . $hometown .'", "category":"'. $topcat .'"}'));
My output is this:
{\"hometown\":\"Seattle, WA\", \"category\":\"Movies\"}"
Not sure where the slashes are coming from (I suppose I can to do stripslashes?) and it seems I need to add '[' and ']' as well? What is the proper formatting for this?
json_encode() takes your array or object, it doesn't accept strings that are already JSON encoded. It can be done like this:
print json_encode(array('hometown' => $hometown, 'category' => $topcat));
Outputs
{"hometown":"Seattle, WA","category":"Movies"}
That string already looks like JSON; why are you trying to encode it again?
Not sure where the slashes are coming from
Because that code encodes a string that contains double-quotes, which must be escaped in JSON.
Unsafe, and dumb, but easy solution:
print('{"hometown":"' . $hometown .'", "category":"'. $topcat .'"}');
Better solution:
print(json_encode(array(
'hometown' => $hometown,
'category' => $topcat,
)));
The string is already formatted as a JSON object, encoding is what is adding the slashes. The json_encode() function is made to convert arrays to JSON objects not strings also whats with the print(), print() is deprecated and echo() should be used.
Here is your solution:
echo '{"hometown":"'.$hometown.'", "category":"'.$topcat.'"}';