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

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;
}

Related

Set multidimensional array in Yii::app()->request->post

I am trying to set multi-dimensional array in Yii post:
Yii::app()->request->post(['PaymentMethodForm'][$_POST['PaymentOptionsForm']['payment_option']]['jazzcash_phone'], $phoneNumber);
to replace traditional $_POST.
$_POST['PaymentMethodForm'][$_POST['PaymentOptionsForm']['payment_option']]['jazzcash_phone'] = $phoneNumber;
$_POST code works fine but Yii post doesn't.
I have to replace all $_POST with Yii post.
Yii::app()->request->post() is GETTING value, with default fallback. It is not setting anything. If You need to populate $_POST array, You should use it directly. More info about request: http://www.yiiframework.com/doc-2.0/guide-runtime-requests.html
Your line Would evaluate to:
$name = $request->post('name', '');
// equivalent to: $name = isset($_POST['name']) ? $_POST['name'] : '';
However, because You are not assigning value to any variable, it does nothing.

PHP POST array with empty and isset [duplicate]

This question already has answers here:
What's the difference between 'isset()' and '!empty()' in PHP?
(7 answers)
Closed 1 year ago.
I have the following multiple checkbox selection:
<input type="checkbox" name="fruit_list[]" value="apple">Apple
<input type="checkbox" name="fruit_list[]" value="banana">Banana
<input type="checkbox" name="fruit_list[]" value="mango">Mango
<input type="checkbox" name="fruit_list[]" value="orange">Orange
form connects to processor.php via POST method. Validation:
if ( empty($_POST['fruit_list']) ){
echo "You must select at least one fruit.<br>";
} else{
foreach ( $_POST['fruit_list'] as $frname ){
echo "Favourite fruit: $frname<br>";
}
}
My Questions (above code works! But unclear points for me):
If I don't select any of checkboxes and then submit form, does $_POST array contain an index called $_POST['fruit_list'] ?
Assuming your answer "No", then how is it possible to use empty() to that non existed array element? Non-existed array element means NULL ?
What is the difference using !isset($_POST['fruit_list']) instead of empty()
I understand the difference between empty() and isset() generally.
Can you explain in this context of example?
If I don't select any of checkboxes and then submit form, does $_POST array contain an index called $_POST['fruit_list']
No, key fruit_list does not exist
To check if key exists in array better use array_key_exists because if you have NULL values isset returns false
But in your case isset is a good way
isset - Determine if a variable is set and is not NULL (have any value).
empty - Determine whether a variable is empty (0, null, '', false, array()) but you can't understand if variable or key exists or not
For example:
$_POST['test'] = 0;
print 'isset check: ';
var_dump(isset($_POST['test']));
print 'empty check: ';
var_dump(empty($_POST['test']));
$_POST['test'] = null;
print 'isset NULL check: ';
var_dump(isset($_POST['test']));
print 'key exists NULL check: ';
var_dump(array_key_exists('test', $_POST));
isset check: bool(true)
empty check: bool(true)
isset NULL check: bool(false)
key exists NULL check: bool(true)
use print_r() to print the post data..
<?php
echo "<pre>"; print_r($_POST);
if (empty($_POST['fruit_list']) ){
echo "You must select at least one fruit.<br>";
}
else{
foreach ( $_POST['fruit_list'] as $frname ){
echo "Favourite fruit: $frname<br>";
}
}
?>
If you do not select any checkbox then you will not get $_POST['fruit_list'], array index fruit_list does not exist in array
for difference between isset() and empty() Visit Here
Answer:
1. $_POST array does not contain $_POST['fruit_list']
2. First answer is "No".A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.see in php.net
3. Empty checks if the variable is set and if it is it checks it for null, "", 0, etc.
Isset just checks if is it set, it could be anything not null. see

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

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)

PHP: a short cut for isset and !empty?

I wonder if there any better ideas to solve the problem below,
I have a form with a number of input fields, such as,
<input name="pg_title" type="text" value="" />
<input name="pg_subtitle" type="text" value="" />
<input name="pg_description" type="text" value="" />
<input name="pg_backdate" type="text" value="" />
etc
But sometimes don't need certain input fields above in my form, for instance, I only need the page title for my db injection,
<input name="pg_title" type="text" value="" />
etc
And I have another php page to handle the $_POST data,
$pg_title = null;
$pg_subtitle = null;
$pg_description = null;
$pg_backdate = null;
if(isset($_POST['pg_title']) && !empty($_POST['pg_title']) ) $pg_title = $_POST['pg_title'];
if(isset($_POST['pg_subtitle']) && !empty($_POST['pg_subtitle']) ) $pg_subtitle = $_POST['pg_subtitle'];
if(isset($_POST['pg_description']) && !empty($_POST['pg_description']) ) $pg_description = $_POST['pg_description'];
if(isset($_POST['pg_backdate']) && !empty($_POST['pg_backdate']) ) $pg_backdate = $_POST['pg_backdate'];
Every time I will have to check if the $_POST of a certain input field is set and not empty, otherwise its variable will be set to null, so that I won't inject an empty space into my DB.
I find the isset and !empty in the if-condition are very repetitive when I have a long list of variables to handle.
Is there any default PHP function to 'shorten' the process above? Or do I have to write a user-defined function to handle this?
Or maybe there is another way to do this?
Just some extra code in my php page that handle the $_POST data,
$sql = "
UPDATE root_pages
SET
pg_url = ?,
pg_title = ?,
pg_subtitle = ?,
pg_backdate = ?,
pg_description = ?,
...
updated_by = ?
WHERE pg_id = ?
";
$result = $connection->run_query($sql,array(
$pg_url,
$pg_title,
$pg_subtitle,
$pg_backdate,
$pg_description,
...
$pg_id
));
as you see that $pg_subtitle, $pg_backdate, $pg_description, etc always present in my query. so if I get $pg_subtitle = '' instead of $pg_subtitle = null when there is no data in it, my db record will have an empty space for that column.
isset && !empty is redundant. The empty language construct is basically shorthand for !isset($foo) || !$foo, with !empty being equivalent to isset($foo) && $foo. So you can shorten your code by leaving out the isset check.
A much simpler way is:
$values = array('pg_title' => null, 'pg_subtitle' => null, …);
$values = array_merge($values, $_POST);
// use $values['pg_title'] etc.
If you don't want your default null values to be overwritten by falsey values, e.g. '', you can do something like this:
$values = array_merge($values, array_filter($_POST));
Just be aware that '0' is falsey as well.
You can use a simple function
function post_value_or($key, $default = NULL) {
return isset($_POST[$key]) && !empty($_POST[$key]) ? $_POST[$key] : $default;
}
Then use:
$pg_title = post_value_or('pg_title');
// OR with a default
$pg_title = post_value_or('pg_title', 'No Title');
empty($var) is an abbreviation for !( isset($var) && $var ).
So !empty($_POST['...']) will be sufficient for your situation — the isset call you have currently is redundant.
User-defined function, I 'm afraid. But they come out short enough. I have one lying around somewhere if you want to take a look, but it's really trivial as you can imagine.
Update:
Here's one I found:
define('PARAM_INT', 0);
define('PARAM_STR', 1);
function get_param($name, $default = null, $type = PARAM_INT) {
$value = $default;
if (isset($_POST[$name])) {
$value = $_POST[$name];
}
else if (isset($_GET[$name])) {
$value = $_GET[$name];
}
switch($type) {
case PARAM_INT:
$value = (int)$value;
break;
case PARAM_STR:
break;
default:
// error your heart out here
}
return $value;
}
Of course now all the cool kids do it with filter_var, but the idea is the same.
+1 for array_merge() but I think that nevertheless short form for:
if (isset($_POST['some_var']) and !empty($_POST['some_var'])) $some_var = $_POST['some_var'];
else $some_var = NULL;
should be:
$some_var = $_POST['some_var'] ? $_POST['some_var'] : NULL;
yes, it causes "undefined index" notice, but it checks for both existance and emptiness
EDIT: and returns NULL of course, as OP asked.
During a small research, I've found an interesting "Control Flow Function" for this case, I've never used before: NULLIF()
So you can perform this task without PHP. Just wrap all variables in it:
NULLIF('".$_REQUEST['some_var']."', '')
in your query instead of '".$_REQUEST['some_var']."'
If variable is empty or doesn't exist it will be NULLIF('', '') as far as '' == '' it will return NULL. Otherwise it will return first arg == your variable.
Consider using the available-by-default filter extension's filter_input function. You'll avoid the missing index Notice and get data sanitization at the same time.
I do not have enough rep to comment. However, the suggestion that vladkras made to use:
$some_var = $_POST['some_var'] ? $_POST['some_var'] : NULL;
is not E_ALL compliant. You should be checking array keys before accessing them using either empty() or isset() as others have suggested. Especially for user input.
Also, his second suggestion to use the MySQL function "NULLIF()" as in the following manner:
NULLIF('".$_REQUEST['some_var']."', '')
is even worse. Inserting unsanitized user input directly into a SQL query is a primary vector for a SQL injection attack.
I'm always making myself unpoular with that. But the best approach is to get over the micro optimization mantra and use the syntax construct which was devised for that #.
Factually I'm lying. I'm all too often using isset() myself. (But at least I know it's not very bright.)
And for new projects I'm now using object-oriented superglobals, which combine filtering and implicit isset tests into $_POST, $_GET, $_REQUEST wrappers. $_REQUEST->ascii["title"] or $_GET["raw"] don't bring up debug messages anymore.
This function check if variable is set, is not empty, eventually if has any value.
/**
* #param var - testing variable
* #param value
* #return boolean
*/
function is(&$var, $value = null){
if(!is_null($value)){ return IsSet($var) && $var == $value; }
return IsSet($var) && !empty($var);
}
echo $_GET['id']; // this produce Warning
echo is($_GET['id'])?'1':'0'; // return false
echo $_GET['id']; // after first using function is(), will not be produce Warning!!!
is($_GET['id']); // return false
IsSet($_GET['id']); // return false
$_GET['id'] = 7;
is($_GET['id'], 7); // return true;

What does ? ... : ... do? [duplicate]

This question already has answers here:
What are the PHP operators "?" and ":" called and what do they do?
(10 answers)
Closed 5 years ago.
$items = (isset($_POST['items'])) ? $_POST['items'] : array();
I don't understand the last snippet of this code "? $_POST['items'] : array();"
What does that combination of code do exactly?
I use it to take in a bunch of values from html text boxes and store it into a session array. But the problem is, if I attempt to resubmit the data in text boxes the new array session overwrites the old session array completely blank spaces and all.
I only want to overwrite places in the array that already have values. If the user decides to fill out only a few text boxes I don't want the previous session array data to be overwritten by blank spaces (from the blank text boxes).
I'm thinking the above code is the problem, but I'm not sure how it works. Enlighten me please.
This is a ternary operator:
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
That last part is known as the conditional operator. Basically it is a condensed if/else statement.
It works like this:
$items =
// if this expression is true
(isset($_POST['items']))
// then "$_POST['items']" is assigned to $items
? $_POST['items']
// else "array()" is assigned
: array();
Also here is some pseudo-code that may be simpler:
$items = (condition) ? value_if_condition_true : value_if_condition_false;
Edit: Here is a quick, pedantic side-note: The PHP documentation calls this operator a ternary operator. While the conditional operator is technically a ternary operator (that is, an operator with 3 operands) it is a misnomer (and rather presumptive) to call it the ternary operator.
It is the same as:
if (isset($_POST['items']){
$items = $_POST['items'];
} else {
$items = array();
}
Look at Paolo's answer to understand the ternary operator.
To do what you are looking at doing you might want to use a session variable.
At the top of your page put this (because you can't output anything to the page before you start a session. I.E. NO ECHO STATEMENTS)
session_start();
Then when a user submits your form, save the result in this server variable. If this is the first time the user submitted the form, just save it directly, otherwise cycle through and add any value that is not empty. See if this is what you are looking for:
HTML CODE (testform.html):
<html>
<body>
<form name="someForm" action="process.php" method="POST">
<input name="items[]" type="text">
<input name="items[]" type="text">
<input name="items[]" type="text">
<input type="submit">
</form>
</body>
</html>
Processing code (process.php):
<?php
session_start();
if(!$_SESSION['items']) {
// If this is the first time the user submitted the form,
// set what they put in to the master list which is $_SESSION['items'].
$_SESSION['items'] = $_POST['items'];
}
else {
// If the user has submitted items before...
// Then we want to replace any fields they changed with the changed value
// and leave the blank ones with what they previously gave us.
foreach ($_POST['items'] as $key => $value) {
if ($value != '') { // So long as the field is not blank
$_SESSION['items'][$key] = $value;
}
}
}
// Displaying the array.
foreach ($_SESSION['items'] as $k => $v) {
echo $v,'<br>';
}
?>
yup... it is ternary operator
a simple and clear explanation provided here, in which the author said it is like answering : “Well, is it true?”
the colon separates two possible values (or). the first value will be chosen if the test expression is true. the second (behind the colon) will be chosen if the first answers is false.
ternary operator very helpfull in creating variable in php 7.x, free of notice warning. For example"
$mod = isset($_REQUEST['mod']) ? $_REQUEST['mod'] : "";
Basically if $_POST['items'] exists then $items gets set to it otherwise it gets set to an empty array.
It is a ternary operator that essentially says if the items key is in the $_POST then set $items to equal the value of $_POST['items'] else set it to a null array.
I figured it's also worth noting that ?: is a separate operator, where:
$one = $two ?: $three;
$one = two() ?: three();
is shorthand for:
$one = $two ? $two : $three;
$one = two() ? two() : three();
Aside from typing less, the runtime advantage is that, if using a function like two(), the function would only be evaluated once using the shorthand form, but possibly twice using the long form.

Categories