Getting array param out of query string with PHP - php

(NOTE: This is a follow up to a previous question, How to pass an array within a query string?, where I asked about standard methods for passing arrays within query strings.)
I now have some PHP code that needs to consume the said query string- What kind of query string array formats does PHP recognize, and do I have to do anything special to retrieve the array?
The following doesn't seem to work:
Query string:
?formparts=[a,b,c]
PHP:
$myarray = $_GET["formparts"];
echo gettype($myarray)
result:
string

Your query string should rather look like this:
?formparts[]=a&formparts[]=b&formparts[]=c

If you're dealing with a query string, you are looking at the $_GET variable. This will contain everything after the ? in your previous question.
So what you will have to do is pretty much the opposite of the other question.
$products = array();
// ... Add some checking of $_GET to make sure it is sane
....
// then assign..
$products = explode(',', $_GET['pname']);
and so on for each variable. I must give you a full warning here, you MUST check what comes through the $_GET variable to make sure it is sane. Otherwise you risk having your site compromised.

Related

Laravel pagination: Append query parameter without value

I have a pagination-instance where I want to append all query parameter from the request to the next_page_url attribute.
I have query parameter with a value like &name=chris but I also have single parameter without a value like &xyz.
However, when I append all query parameters to the pagination instance, like so:
$query->simplePaginate(50)->appends($request->all());
only parameters with a value are getting appended.
How can I append all parameters to the next_page_url?
Update
I want to append query parameters to get the next chunk of requested data.
If I don't, it always gives back "next_page_url":"http://vue.dev/contacts?page=2". What I want is "next_page_url":"http://vue.dev/contacts?name&page=2"
Take URL http://vue.dev/contacts?page=2&name for example. Although perfectly valid, it's still quite ambiguous. Do we mean to include name? Do we mean to exclude name?
So I'd suggest you to use this URL instead http://vue.dev/contacts?page=2&select=name. If you decide to select more stuff you can just do http://vue.dev/contacts?page=2&select=name,age,gender.
Later in your code just use explode to use the value as an array:
$attributes = explode(',', $request->select);
Useful reading: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
Even though Fahmis solution is possible as well, I end up using the approach from this so-question. This has the advantage that php reads the parameter as an array automatically. My url end up looking like this:
http://vue.dev/contacts?page=2&select[]=xyz&select[]=abc

php variable in an array

$q2=$_REQUEST['binge'];
'book2'=>array('callno'=>123006,'price'=>number_format(844,2),'desc'=>'Binge','auth'=>'Tyler Oakley','quant'=>$q2,'total'=>number_format(844,2)*$q2)
On this particular code, It kept displaying errors like this
Warning: A non-numeric value encountered in C:\xampp\htdocs\Webcard_3new\Webcard\wishlist.php on line 97
I searched all over the net for finding the right answers but some are just so complex to understand...
It supposed to be that $q2 is the variable inside an array. That variable is then multiplied to the "TOTAL". but the errors kept on going.. please help!!
The super-globals will always be strings. You need to explicitly convert them using intval():
$q2 = intval($_REQUEST['binge']);
Also, this line:
'book2'=>array...
Should be
$book2 = array...
You can use
$q2 = filter_var($_REQUEST['binge'], FILTER_VALIDATE_INT);
here you will have the benefit of validation where false is returned when someone passes a value that is not an integer. If it is instead a float use FILTER_VALIDATE_FLOAT instead.
Also, consider using $_GET, or $_POST directly to have more control of the data channel. $_REQUEST cobbles together several things into one, which sometimes may cause issues when more than one channel have the same key.

build SQL statement from json encoded string php

Welcome Stackoverflow nation ! I'm trying to decode json encoded string into SQL statement withing php.
Lets say I've such a json encoded string =>
$j = '{"groupOp":"AND","rules":[{"field":"id","op":"cn","data":"A"},{"field":"i_name","op":"cn","data":"B"}]}';
I want to build SQL WHERE clause (needed for filterToolbar search in jqGrid), something like this => "WHERE id LIKE %A% AND i_name LIKE %B% " and etc.
I've done this =>
$d = json_decode($j);
$filterArray = get_object_vars($d); // makes array
foreach($filterArray as $m_arr_name => $m_arr_key){
// here I can't made up my mind how to continue build SQL statement which I've mentioned above
}
Any ideas how to do that , thanks preliminarily :)
The first problem is you will want to pull out the groupOp operator.
Then, you have an object and inside that you have an array of objects, so you may want to look at the results of filterArray as that won't have the value you want.
Then, when you loop through, you will want to do it with an index so you can just pull the values out in order.
You may want to look at this question to see how you can get data out of the array:
json decode in php
And here is another question that may be helpful for you:
How to decode a JSON String with several objects in PHP?
There is an answer with an implementation for the server-side php code here
Correction: I had to unescape double-quotes in the 'filters' parameter to get it working:
$filters = str_replace('\"','"' ,$_POST['filters']);

Find and concatenate result in a pattern

I have a long PHP file and I want to copy all the variable names only and build an insert sql query. Is there a way where I can search for a pattern using regular expression and concatenate the find result till I collected all the variable and spit it out in a statement?
I am using TextMate and am familiar with regular expression search. Regex search result give $0,$1 and so forth argument. Do not know if this possible though. Solution in any editor will do not just text mate.
I have just too many variable (+100) don't feel like copy every single one. Here my sample file
$ID = $_POST['id'];
$TXN_TYPE = $_POST['txn_type'];
$CHARSET = $_POST['charset']
$CUSTOM = $_POST['custom'];
You could try something with get_defined_vars(). However this function also lists GLOBAL vars. You can use this snippet to remove them if you don't want them and display only the vars you defined
$variables = array_diff(get_defined_vars(), array(array()));
However this snippet generates Notices and I haven't found a way to solve them yet.
If you've only got $_POST variables you can loop through the $_POST array itself
You create the SQL programmatically while looping through the array.
My own solution is, do the inverse. It is not probably possible.
Leave only the variable names Remove all the rest. Use
[space].+ regex to remove everything that is after the variable name.
clean the file so that only variable names are left. then do a couple more find and replace to bring the variable name in the form you want.
If you're looking to match only the variable names (not the $_POST array indices), then the regular expression is pretty much provided in the PHP documentation:
\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
This will, of course, include $_POST, but that should be easy enough to remove. If not, you could do it with negative lookahead (if TextMate supports it):
\$(?!_POST($|[^a-zA-Z0-9_\x7f-\xff]))[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

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