Is it possible to get empty array value via $_GET? - php

Is it possible to get empty array(array with 0 items) value via $_GET?
Is it possible with direct value setting?
count($_GET['param'])==0

You just need an empty value url = myform.php?param=&param2=
In form just let the value blank:
<input type='text' name='param' value ='' />
For an empty array:
url: myform.php?param[]=&param2[some_key]=
in form: <input type='text' name='param[]' value ='' />
From Ajax: (I remember this was so anti-intuitive and hard to search for):
ajax{
...
data: {'params[]':'','params2[some_key]':''}
}
Workaround:
Just edit the back-end and if there is no data for params or it is not an array (null, empty whatever ..) just assign an empty string to it:
$param = (isset($_GET['param']) && is_array($_GET['param']))? $_GET['param'] : array();
Update:
I did few tests and it seems there is no way to put "nothing" in the request ussing a form or ajax.
0, '', Null are valid values for the $_GET but empty array is not even created.
So to answer your question, it is NOT possible to get empty array value from the front-end.
There are few options to edit $_GET manually in the back-end:
<?php
if(!isset($_GET['param']) || !$_GET['param']){ //not set or (null,0,"")
$_GET['param'] = array();
}
if(count($_GET['param'])==0){...}; // 0 if no 'param' was provided.

If array is empty or containing values that doesn't matters. Just declare a variable and pass the $_GET[] to the variable.
for example,
$para=$_GET['param'];
and now
if(is_array($para))
{
//
}
else{
$para=new array();
}

passing empty array via GET is not possible under normal situation. That said, I can think of a really rare way that the checking you used will return true.
http://domain.com/receiver?param=a%3A0%3A%7B%7D
The above is basically a serialized and urlencoded empty array with the key 'param'
if the target server have some sort of filter that auto unserialize all incoming data, then it might happen.
(or something like the below)
foreach($_GET as $key => $value){
$_GET[$key] = unserialize($value);
}
count($_GET['param'])==0
I know this is a far fetch but it is possible, maybe some private test server that only handles serialized data but accidentally open to public e.t.c.
That said, it is still only passing a serialized empty array instead of a empty array itself. But let's be honest, this answer is more like a joke/fun answer that tries to point out under some very rare case
count($_GET['param'])==0
will return true (Without actively assigning values # server side)

Related

empty text input means empty $_POST[] element? (Null coallesce)

So my question is:
If I don't write anything in an input
<input type="text" name="test">
in a simple form with post method, when I receive the $_POST array in my action url, the $_POST["test"] exists as empty string ($_POST["test"] => "").
So I can't use null coalesce because $var = $_POST["test"] ?? 'default'; because it is always $var = ""; (as is normal).
Any way to solve this problem?
for Only check if a PARTICULAR Key is available in post data
if (isset($_POST['test']) )
{
$textData = '+text'.$_POST['test'];
echo $textData;
}

Array PHP, if array changes

Is there a way to execute a code only when my array has a new value passed on in position [0];?
if(?){
print_r(array_values($parcels)[0]);
} else{}
tried multiple statements but all lead to error or invalid. If a new order comes in array[0] gets replaced with that info. So only when that info has changed execute this.. Is this Possible?
You need to store the old value in an other variable to compare it. So you are able to consider if the value has changed.
$oldValue = $parcels[0];
//-------
//Code that eventually changes the array
//-------
if($oldValue != $parcels[0]) {
print_r(array_values($parcels)[0]);
$oldValue = $parcels[0];
} else{}

How to access all values posted to PHP server

I first thought it was in the $_POST super global, but it isn't if values are included in the URL.
$_REQUEST did so and surprised me by not including cookies (reference http://php.net/manual/en/reserved.variables.request.php), and I later found that I am evidently using the default distribution php.ini file which does not contain the 'C' for cookies (reference http://php.net/manual/en/ini.core.php#ini.request-order). I don't wish to use $_REQUEST, however, as it doesn't differentiate between a get request, and changing servers and php.ini files could cause a security concern.
What is the proper way to access all post values?
EDIT. I added the $real_post part. Is this the proper way to do so?
<?php
setcookie('cookie', 'COOKIE', time() + (86400 * 30), "/");
echo('$_GET<pre>'.print_r($_GET,1).'</pre>');
echo('$_POST<pre>'.print_r($_POST,1).'</pre>');
echo('$_COOKIE<pre>'.print_r($_COOKIE,1).'</pre>');
echo('$_REQUEST<pre>'.print_r($_REQUEST,1).'</pre>');
$real_post=($_SERVER['REQUEST_METHOD'] == 'POST')?array_merge($_GET,$_POST):array();
echo('$real_post<pre>'.print_r($real_post,1).'</pre>');
?>
<form action='postorget.php?get=GET' method='post'>
<input type='text' name='post' value='POST'>
<input type='submit'>
</form>
$_GET
Array (
[get] => GET )
$_POST
Array (
[post] => POST )
$_COOKIE
Array (
[cookie] => COOKIE )
$_REQUEST
Array (
[get] => GET
[post] => POST )
You could do something like:
$uVariables = array("GET" => $_GET, "POST" => $_POST, "COOKIES" => $_COOKIES, "SESSION" => $_SESSION);
and then use json_encode() for database storage. Should you later decide to build a log viewer you can just use json_decode() and get everything back in original state.
Sorry, your question is a little unclear. Parameters appended to the URL (as you mention in the beginning) are GET parameters, so they are contained in the $_GET superglobal. They simply are not POST variables. So what is your question here? You could combine $_POST and $_GET or, preferred, check for a desired parameter in both locations.
You can invest endless time into stuff like this, but a convenient approach might look like this:
$param = isset($_GET['param']) ? $_GET['param']
: (isset($_POST['param']) ? $_POST['param']
: null);
This line is just an example. It retrieves a parameter called 'param' from the super globals $_GET or $_POST and stores it in the variable $params in the local scope. This way you can access any parameter you are looking for regardless if it is sent as a GET or as a POST parameter. I often wrap that in a convenience function which also takes care of validating the parameters runtime value.
You could also wrap this example in an iteration loop:
$params = [
'id' => null,
'key' => null,
'value' => null,
'remark' => null
]; // just as examples
foreach ($params as $key=>$null) {
// alternative 1: store the value of param $key in a single local scalar variable
// this results in local variables $id, $key, $value, $remark, just as examples
$$key = isset($_GET[$key]) ? $_GET[$key]
: (isset($_POST[$key]) ? $_POST[$key]
: null);
// alternative 2: store the value of param $key in a general but local params array
// this results in the above $params array, but filled with scalar values
$params[$key] = isset($_GET[$key]) ? $_GET[$key]
: (isset($_POST[$key]) ? $_POST[$key]
: null);
}
These are actually two examples. Obviously you need only one of the two statements shown inside the loop here. This depends on whether you prefer an array of params or separate local scalar variables.
If you are looking for a way to get all GET and POST parameters without actually knowing which that might be, then you have to combine the two super globals:
$params = array_merge($_GET, $_POST);
Note however that this is a very questionable architecture. It typically opens security holes.

PHP isset not working properly on form, with loops and arrays

This is honestly the most finicky and inept language I've ever coded in. I'll be glad when this project is good and over with.
In any case I have to us PHP so here's my question.
I have an Array named $form_data as such:
$form_data = array
('trav_emer_med_insur',
'trav_emer_single',
'trav_emer_single_date_go',
'trav_emer_single_date_ba',
'trav_emer_annual',
'trav_emer_annual_date_go',
'trav_emer_extend',
'trav_emer_extend_date_go',
'trav_emer_extend_date_ef',
'trav_emer_extend_date_ba',
'allinc_insur',
'allinc_insur_opt1',
'allinc_single_date_go',
'allinc_single_date_ba',
'allinc_insur_opt2',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'cancel_insur',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'visitor_insur',
'country_select',
'visitor_supervisa',
'visitor_supervisa_date_go',
'visitor_supervisa_date_ba',
'visitor_student',
'visitor_student_date_go',
'visitor_student_date_ba',
'visitor_xpat',
'visitor_xpat_date_go',
'visitor_xpat_date_ba',
'txtApp1Name',
'txtApp2Name',
'txtApp1DOB',
'txtApp2DOB',
'txtApp1Add',
'txtApp1City',
'selprov',
'txtApp1Postal',
'txtApp1Phone',
'txtApp1Ext',
'txtApp1Email',
'conpref', );
These are the names of name="" fields on an HTML form. I have verified that ALL names exist and have a default value of '' using var_dump($_POST).
What I want to do is very simple, using the $form_data as reference do this:
create a new array called $out_data which can handle the data to display on a regurgitated form.
The structure of $out_data is simple the key will be the name of the element from the other array $out_data[txtApp1Name] for example, and then the value of that key will be the value.
Now what I want is to first check to see if every name="" is set or not, to eliminate errors and verify the data. Then regardless of whether it is set or not, create its placeholder in the $out_data array.
So if $_POST[$form_data[1]] (name is 'trav_emer_single') is not set create an entry in $out_data that looks like this $out_data([trav_emer_single] => "NO DATA")
If $_POST[$form_data[1]] (name is 'trav_emer_single') is set create and entry in $out_data that looks like this: $out_data([trav_emer_single] => "whatever the user typed in")
I have tried this code:
$out_data = array();
$count = count($form_data);
for( $i = 0; $i < $count; $i++ )
{
if(!isset($_POST[$form_data[$i]])) {
$out_data[$form_data[$i]] = "NO_DATA";
}
else {
$out_data[$form_data[$i]] = $_POST[$form_data[$i]];
}
}
Now this code technically is working, it is going through the array and assigning values, but it is not doing so properly.
I have hit submit on the form with NOTHING entered. Therefore every item should say "NO_DATA" on my regurgitated output (for user review), however only some items are saying it. All items I have confirmed have name="" and match the array, and have nothing entered in them. Why is "NO_DATA" not being assigned to every item in the array?
Also of note, if I fill in the form completely $out_data is fully and correctly populated. What is the problem with !isset? I've tried doing $_POST[$form_data[$i]] == '' which does put no_data in every instance of no data, however it throws an 'undefined index' warning for every single item on the page whether I write something in the box or not.
Really I just want to know WTF is going on, the dead line for this project is closing fast and EVERY step of the PHP gives me grief.
As far as I can tell by reading around my code is valid, but refuses to execute as advertised.
If you need more code samples please ask.
Really befuddled here, nothing works without an error, help please.
Thanks
-Sean
Instead of checking !isset(), use empty(). If the form posts an empty string, it will still show up in the $_POST as an empty string, and isset() would return TRUE.
I've replaced your incremental for loop with a foreach loop, which is almost always used in PHP for iterating an array.
$out_data = array();
foreach ($form_data as $key) {
if(empty($_POST[$key])) {
$out_data[$key] = "NO_DATA";
}
else {
$out_data[$key] = $_POST[$key];
}
}
PHP's isset returns TRUE unless the variable is undefined or it is NULL. The empty string "" does not cause it to return FALSE. empty() will do exactly what you need, though.
http://php.net/manual/en/function.isset.php
isset() will return FALSE if testing a variable that has been set to
NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP
NULL constant.
Returns TRUE if var exists and has value other than NULL, FALSE
otherwise.

Evaluate a dynamic array key

I have a form that allows the user to add information an their leisure. They can add locations via jQuery in my form so when recieving the data I may have 1 location or 10. Each location has attributes like phone, address, etc. In my form the input names are appended with _1 , _2, etc to show its a new set of data. That is working swimmingly and I just can't seem to find these keys when looping through the $_POST array
private function array_pluck($arr,$text)
{
foreach($arr as $key => $item)
{
if(stripos($key,$text) != 0)
{
$found[] = $item;
}
}
return $found;
}
As I understand it if my array has some keys "office_branch_phone_1, office_branch_phone_2" I should be able to put in "office_branch" in my $text param and it will spit out any keys with the "office_branch" in the name. This isn't working however and I'm a bit stumped.
Since stripos will return the index (and it is a 0-based index returned) != 0 is incorrect.
if (stripos($key,$text) !== false)
Would be the correct way to check it. Give that a shot.
EDIT
Note the use of !== instead of != since 0 tends to be considered false if loosely checked the !== will check the actual type, so 0 is a valid return. Just an extra tidbit of information

Categories