http_build_query without value on parameters (null value) - php

The PHP function http_build_query is quite handy for building an URL with GET parameters. But sometimes I like to use value-less "boolean" parameters, like so:
/mypage?subscription-id=42&cancel-renewal
Which I then check with a simple isset. Can I achieve this result with http_build_query?
EDIT: Assigning empty values to the parameter does not seem to work :
cancel-renewal => '' results in cancel-renewal=
cancel-renewal => null results in the parameter being omitted
cancel-renewal => false results in cancel-renewal=0

Can I achieve this result with http_build_query?
No. Internally http_build_query appends the = key-value separator no matter what is the value of the parameter.
You can see the source code here (PHP 7.3.3)
Means you either need to accept the cancel-renewal= look of the parameter or may be redesign the path to have something like /mypage/cancel-renewal?subscription-id=42
Third option would be to write your own simple function to build the query string.

Use this;
$query = array("subscription-id" => 42, "cancel-renewal" => "");
$http_query = http_build_query($query);
This will return ?subscription-id=42&cancel-renewal=. And works perfectly fine with isset()

Related

PHP http_build_query() generate incorrect url for array get parameter

I probably discovered a bug of a PHP function http_build_query().
I am developing a search engine with dynamic form and some of these parameters are array.
I simply get the query url from the current $_GET with http_build_query().
But all of these array parameters are automatically changed from "arrayName%5B%5D" to "arrayName%5B0%5D" in the new query generated.
$queryStr = http_build_query($_GET);
original url
&arrayName%5B%5D=
new query string got from http_build_query():
&arrayName%5B0%5D=
What is the reason for this? How to fix this?
It's not a bug to http_build_query() function.
When you pass the get parameter via URL like: "arrayName[]="
print_R($_GET);
will return
Array
(
[arrayName] => Array
(
[0] =>
)
)
and http_build_query generates the url encoded string from array, the result is:
&arrayName%5B0%5D=
and decoded this looks like:
arrayName[0]=
Now you can see where the 0 came from :)
There is no need to fix this, you can change your code to pass keys for the arrayName or still use it as is.
Suppose we are using multiple checkboxes with ASC/DESC orders.
For that previously provided solution not working.
$queryStr = http_build_query($_GET);
$queryStr = urldecode($queryStr);
$queryStr = preg_replace('/[[0-9]+]/', '[]', $queryStr);
This solution works fine for me.
Forex. https://example.com?s=LorumText&post_type[]=blog
// Now your string won't be converted into hashcode(%5B0%5D=), It remains with []
Current Result: https://example.com?s=LorumText&post_type %5B0%5D=blog
Updated Result: https://example.com?s=LorumText&post_type[]=blog

generating url parameters from array

Let's say I have the following array :
$params
= array(
'foo' => 'bar',
'baz' => array('qux', 'qux2', 'qux3')
);
is there a pre-built function in php so :
the_function($params);
outputs
'foo=bar&baz[]=qux&baz[]=qux2&baz[]=qux3'
?
Note : i am asking for a pre-built function, I can code the function myself. Just making sure I am not coding something already existing.
How come nobody suggested this before. http_build_query() is what you were looking for.
$params = array('foo'=>'bar','baz'=>array('qux','qux2','qux3'));
echo urldecode(http_build_query($params));
// foo=bar&baz[0]=qux&baz[1]=qux2&baz[2]=qux3
A few caveats you might have to be aware of :
the resulting string is urlencoded (use urldecode() as I did above if necesary)
array indexes are present in the query string
Some of the comments in the documentation page can help with the latter if needed. http://php.net/manual/en/function.http-build-query.php

How to pass empty parameter through $_POST

In one of the cakePHP framework's view, I take the parameters given by a user and make an action call. Here is how it looks like:
echo $this->Html->link(__('Save as PDF'),array('action'=>'view_as_pdf',$_POST['data']['Event']['employee'],$_POST['data']['Event']['project'],$_POST['data']['Event']['from'],$_POST['data']['Event']['to'],'ext' => 'pdf'));
The problem appears when *$_POST['data']['Event']['employee']* or *$_POST['data']['Event']['project']* project is not provided.
That makes a proper url like:
pdf.com/action/16/77/2014-01-01/2014-01-15
Look like:
pdf.com/action/16/2014-01-01/2014-01-15
What I would like it to look is something like:
pdf.com/action/16/null/2014-01-01/2014-01-15
Replace the items in your array passed into the link method with ternary operator and check the values. Essentially, you need to set a default value if the POSTed value is not set/empty/what-have-you.
You could do something like this:
empty($_POST['data']['Event']['project']) ? 'null' : $_POST['data']['Event']['project']
You need to pass a string of null in order for it to be passed as 'null'. Likely, the underlying code for that link method ignores empty parameters.
Doing it this way will give you the pdf.com/action/16/null/2014-01-01/2014-01-15 url you are looking to achieve.

array values do not work as expected

I've a soap function which expects 3 parameters that should be passed as strings with quotes.
function('id','username','password');
and in another hand i've an array which contains :
[0] = > "'id','username','password'"
[1] = > "'id','username','password'"
....
when i echo $array[0] out put is 'id','username','password' and when i use function('id','username','password'); there is no problem but when i use
function($array[0]); it won't work.
i tested my array with echo, die, print_r ... the output is the same as the function expects!!!!
any help ?
thanks ; )
Simply because it can't work. If you have a function that needs 3 parameters, you can't pass a single parameter. Also if is an array that contains the 3 parameters you need, the function still want and need 3 parameters. Thus, if you give the function an array, it will use just the array as the first one (so you'll have an unexpected behavior) and take the second and the thirs as NULL.
It's true that php is a little bit magic, but can't do miracles.
You need to change the signature of your function.
function('id','username','password');
is a function with three parameters.
function($array[0]);
is a function with only one parameter.

APACHE mod_rewrite change variable name in query string

I'm trying to change a variable name in a query string, so it's usable by my PHP code.
The query gets posts from an external system, so I can't control that they are posting a variable name with a space in it. And that makes it impossible for me to use the PHP $_GET function.
I need to change variable%20name to ?new1
And I need to change variable2 to new2
There are many variables passed in the query, but only these two need to be changed. The rest can stay the same or even disappear.
So ?variable%20name=abc&variable2=xyz
Needs to end up as ?new1=abc&new2=xyz
Also, they may not be in this order and there may be more variables
So ?variable%20name=abc&blah=123&blah2=456&variable2=xyz
Could end up as ?new1=abc&new2=xyz
OR as ?new1=abc&blah=123&blah2=456&new2=xyz
Either way would be fine!
Please give me the mod_rewrite rule that will fix this.
Thank you in advance!
Parsing the query string with mod_rewrite is a bit of a pain, has to be done with RewriteCond and using %n replacements in a subsequent RewriteRule, probably easier to manually break up the original query string in PHP.
The full query string can be found (within PHP) in $_SERVER['QUERY_STRING'].
You can split it up using preg_split() or explode(), first on &, then on =, to get key/value pairs.
Using custom%20cbid=123&blahblahblah&name=example as an example.
$params = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $cKeyValue) {
list ($cKey, $cValue) = explode('=', $cKeyValue, 2);
$params[urldecode($cKey)] = urldecode($cValue);
}
// Would result in:
$params = array('custom cbid' => 123,
'blahblahblah' => NULL,
'name' => example);

Categories