I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.
something like this:
$fromPerson = '+from%3A'.$_POST['fromPerson'];
function fromPerson() {
if !($_POST['fromPerson']) {
print ''
} else {
print $fromPerson
};
}
$newString = fromPerson();
Any help would be great!
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Simple. You've two choices:
1. Check if there's ANY post data at all
//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
// handle post data
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
(OR)
2. Only check if a PARTICULAR Key is available in post data
if (isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Surprised it has not been mentioned
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
Everyone is saying to use isset() - which will probably work for you.
However, it's important that you understand the difference between
$_POST['x'] = NULL; and $_POST['x'] = '';
isset($_POST['x']) will return false on the first example, but will return true on the second one even though if you tried to print either one, both would return a blank value.
If your $_POST is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.
Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.
isset($_POST['fromPerson'])
The proper way of checking if array key exists is function array_key_exists()
The difference is that when you have $_POST['variable'] = null it means that key exists and was send but value was null
The other option is isset() which which will check if array key exists and if it was set
The last option is to use empty() which will check if array key exists if is set and if value is not considered empty.
Examples:
$arr = [
'a' => null,
'b' => '',
'c' => 1
];
array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true
array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true
array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false
Regarding your question
The proper way to check if value was send is to use array_key_exists() with check of request method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)
{
// logic
}
But there are some cases depends on your logic where isset() and empty() can be good as well.
In that case using method isset is not appropriate.
According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).
All the methods are actually discouraged, it's a warning in Netbeans 7.4 and it surely is a good practice not to access superglobal variables directly, use a filter instead
$fromPerson = filter_input(INPUT_POST, 'fromPerson', FILTER_DEFAULT);
if($fromPerson === NULL) { /*$fromPerson is not present*/ }
else{ /*present*/ }
var_dump($fromPerson);exit(0);
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
I would like to add my answer even though this thread is years old and it ranked high in Google for me.
My best method is to try:
if(sizeof($_POST) !== 0){
// Code...
}
As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.
You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.
$_POST always exists in itself being either empty or has array values.
$_POST['value'] may not exist, thus throwing an "undefined index" error.
Try isset($_POST['fromPerson'])?
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
if( isset($_POST['fromPerson']) ) is right.
You can use a function and return, better then directing echo.
I like to check if it isset and if it's empty in a ternary operator.
// POST variable check
$userID = (isset( $_POST['userID'] ) && !empty( $_POST['userID'] )) ? $_POST['userID'] : null;
$line = (isset( $_POST['line'] ) && !empty( $_POST['line'] )) ? $_POST['line'] : null;
$message = (isset( $_POST['message'] ) && !empty( $_POST['message'] )) ? $_POST['message'] : null;
$source = (isset( $_POST['source'] ) && !empty( $_POST['source'] )) ? $_POST['source'] : null;
$version = (isset( $_POST['version'] ) && !empty( $_POST['version'] )) ? $_POST['version'] : null;
$release = (isset( $_POST['release'] ) && !empty( $_POST['release'] )) ? $_POST['release'] : null;
I recently came up with this:
class ParameterFetcher
{
public function fetchDate(string $pDate):string{
$myVar = "";
try{
if(strlen($_POST[$pDate]) > 0){
$myVar = $_POST[$pDate];
}
}catch (Exception $faild){
die("field NULL or not set for $pDate");
}
[ ... other stuff ]
to fetch a date obviously, but it can take ANY post param. You can also check for GET this way.
Related
I am building a page where GET parameters are used and i am wondering if this piece of code successfully evaluates the next conditions: $_GET["id"] must be an integrer and $_GET["status"] must be a "true" or "false".
$rawId = $_GET["id"];
$rawStatus = $_GET["status"];
$Id = filter_var($rawId, FILTER_SANITIZE_NUMBER_INT);
$Id = filter_var($Id, FILTER_VALIDATE_INT);
if (!$Id) {
die();
}
if ($rawStatus != "true" && $rawStatus != "false") {
die();
}
You can use is_int and is_bool to achieve this. Make sure you are also checking if the $_GET vars are set before you do this to avoid potential notices
$rawId = (isset($_GET["id"]) ? $_GET["id"] : null);
$rawStatus = (isset($_GET["status"]) ? $_GET["status"] : null);
if (!is_int($rawId)) {
//handle
}
if (!is_bool($rawStatus)) {
//handle
}
FILTER_SANITIZE_NUMBER_INT allows for ., + and -, which you probably don't want to include. Using FILTER_VALIDATE_INT would be fine for regular integer checks, though keep in mind that this will return false for 0. If you want your IDs to also include 0, then you'll need to explicitly check for this:
$Id = filter_var($rawId, FILTER_VALIDATE_INT) === 0 || filter_var($rawId, FILTER_VALIDATE_INT));
Assuming you want $rawStatus to be a literal string of true / false, then the way you have it covered at the moment is probably the most optimal approach, though it sounds like you're trying to make a boolean check here. In this case, you can simply check for the presence of $rawStatus, using the lack of its presence to denote a falsy value:
if ($rawStatus)
And as you mention in your comment, you will indeed want to check that both are set with isset()... but you'll also want to check that the values are not empty. This can be done with !empty().
I'd also recommend only proceeding in a know valid state, rather than calling die() in a known invalid state.
Putting this all together, you'll have something that looks like the following:
$rawId = null;
if (isset($_GET["id"]) && !empty($_GET["id"])) {
$rawId = $_GET["id"];
}
if (isset($_GET["status"]) && !empty($_GET["status"])) {
$rawStatus = $_GET["status"];
}
$Id = filter_var($rawId, FILTER_VALIDATE_INT) === 0 || filter_var($rawId, FILTER_VALIDATE_INT);
if ($Id && $rawStatus) {
// Logic
}
If you need to check the type of $rawId and $rawStatus you can do it
is_integer($rawId); // return true if $rawId is integer
is_bool($rawStatus); // return true if $rawStatus is boolean
To check if $rawId has only numbers you can do it
is_numeric($rawId)
To check if $rawStatus is bool you can see this answer
Test if string could be boolean PHP
If is needed to parse the values you can use intval() and boolval()
I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.
something like this:
$fromPerson = '+from%3A'.$_POST['fromPerson'];
function fromPerson() {
if !($_POST['fromPerson']) {
print ''
} else {
print $fromPerson
};
}
$newString = fromPerson();
Any help would be great!
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Simple. You've two choices:
1. Check if there's ANY post data at all
//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
// handle post data
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
(OR)
2. Only check if a PARTICULAR Key is available in post data
if (isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Surprised it has not been mentioned
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
Everyone is saying to use isset() - which will probably work for you.
However, it's important that you understand the difference between
$_POST['x'] = NULL; and $_POST['x'] = '';
isset($_POST['x']) will return false on the first example, but will return true on the second one even though if you tried to print either one, both would return a blank value.
If your $_POST is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.
Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.
isset($_POST['fromPerson'])
The proper way of checking if array key exists is function array_key_exists()
The difference is that when you have $_POST['variable'] = null it means that key exists and was send but value was null
The other option is isset() which which will check if array key exists and if it was set
The last option is to use empty() which will check if array key exists if is set and if value is not considered empty.
Examples:
$arr = [
'a' => null,
'b' => '',
'c' => 1
];
array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true
array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true
array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false
Regarding your question
The proper way to check if value was send is to use array_key_exists() with check of request method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)
{
// logic
}
But there are some cases depends on your logic where isset() and empty() can be good as well.
In that case using method isset is not appropriate.
According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).
All the methods are actually discouraged, it's a warning in Netbeans 7.4 and it surely is a good practice not to access superglobal variables directly, use a filter instead
$fromPerson = filter_input(INPUT_POST, 'fromPerson', FILTER_DEFAULT);
if($fromPerson === NULL) { /*$fromPerson is not present*/ }
else{ /*present*/ }
var_dump($fromPerson);exit(0);
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
I would like to add my answer even though this thread is years old and it ranked high in Google for me.
My best method is to try:
if(sizeof($_POST) !== 0){
// Code...
}
As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.
You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.
$_POST always exists in itself being either empty or has array values.
$_POST['value'] may not exist, thus throwing an "undefined index" error.
Try isset($_POST['fromPerson'])?
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
if( isset($_POST['fromPerson']) ) is right.
You can use a function and return, better then directing echo.
I like to check if it isset and if it's empty in a ternary operator.
// POST variable check
$userID = (isset( $_POST['userID'] ) && !empty( $_POST['userID'] )) ? $_POST['userID'] : null;
$line = (isset( $_POST['line'] ) && !empty( $_POST['line'] )) ? $_POST['line'] : null;
$message = (isset( $_POST['message'] ) && !empty( $_POST['message'] )) ? $_POST['message'] : null;
$source = (isset( $_POST['source'] ) && !empty( $_POST['source'] )) ? $_POST['source'] : null;
$version = (isset( $_POST['version'] ) && !empty( $_POST['version'] )) ? $_POST['version'] : null;
$release = (isset( $_POST['release'] ) && !empty( $_POST['release'] )) ? $_POST['release'] : null;
I recently came up with this:
class ParameterFetcher
{
public function fetchDate(string $pDate):string{
$myVar = "";
try{
if(strlen($_POST[$pDate]) > 0){
$myVar = $_POST[$pDate];
}
}catch (Exception $faild){
die("field NULL or not set for $pDate");
}
[ ... other stuff ]
to fetch a date obviously, but it can take ANY post param. You can also check for GET this way.
How do I check if $_GET superglobal variable is set and when it doesn't equal 0-100-euro?
Unsuccessful example:
if( !isset($_GET['preis'] ) AND $_GET['preis'] === "0-100-euro" );
I think you're looking for this:
if($_GET['preis'] !== "0-100-euro") {
echo "your message";
}
I think that it is better to check if a key exists, because if you use "isset()" PHP can return a notice message: "Undefined index".
<?php
if (!array_key_exists('preis', $_GET) || $_GET['preis'] !== '0-100-euro') {
die('"preis" is not set or is equal to "0-100-euro".');
}
Use OR, not AND, and reverse the test of the value.
if (!isset($_GET['preis') || $_GET['preis' != '0-100-euro')
Don't they teach deMorgan's Law any more?
$_GET['preis'] != "0-100-euro"
Right now, you try to see if the variable does not exist AND if it contains "0-100-euro". It will always return false. Just change == by !=.
You could do that by using sleek shortcuts:
isset( $_GET['preis'] ) && ( isset($_GET['preis'] ) && $_GET['preis'] != "0-100-euro" ) ? $result = true : $result = false;
Later you can check your request and in case it's not what you wanted, it will print:
isset( $result ) && print ( "0-100-euro is not set" );
I have the following $_POST function to check if the fields of 'start', 'middle' and 'end' is empty or not.
if(!empty($_POST['start'])) {
$description = "a sentence".$_POST['start']." with something in the START.";
}
if(!empty($_POST['middle'])) {
$description = "a sentence".$_POST['middle']." with something in the MIDDLE.";
}
if(!empty($_POST['end'])) {
$description .= "a sentence".$_POST['end']." with something in the END.";
}
I want to check the values in one function, in other words I want to check multiple values at the same time. I have seen few method but not sure which one is right, using comma or && or ||, something like below ...
if(!empty($_POST['start']) , (!empty($_POST['middle']) , (!empty($_POST['end']))
or
if(!empty($_POST['start']) && (!empty($_POST['middle']) && (!empty($_POST['end']))
or
if(!empty($_POST['start']) || (!empty($_POST['middle']) || (!empty($_POST['end']))
Can anyone tell me the right code for this kind of formation?
here are some basic.. i made it as a comment(as i was not sure if this is the thing you asked for) but i guess an answer would be appropriate with a bit of details.
the AND operatior
the && will check every condition and if all are true it will return true...
take it like this
if(FALSE && TRUE)
it will always return False and if will not execute because one of the condition is false
The OR operator
THe || will check the first condition if its true it will return true else check the second condition If all are false(not even a single is true) it will return false.
again following the previous example
if(TRUE || False || False)
now the compiler checks the first condition if its true it will ignore the next two conditions and return true.
if(FALSE || FALSE || FALSE) - this will return false as all are false
THe comma Operator
if you , operatior then the last condition to the right will be evaluated and if it is true then it will return true else false
example
if(True,True,True,False) - it will return false
if(FALSE, TRUE, FALSE, TRUE) - it will return true
so choose the operator according to your logic.
USE THIS :
if((!empty($_POST['start'])) && (!empty($_POST['start'])) && (!empty($_POST['start'])));
Your looking for something like:
// Establish valid post key values
$valid_post_variables = array_flip( ['start', 'middle', 'end'] );
// Fetch post data
$post = $_POST;
// $result will contain the values of post where the keys matched valid
$result = array_intersect_key( $post, $valid_post_variables );
// if the resulting array contains our 3 options, its go time
if ( count( $result ) == 3 ) {
//start middle and end where all passed via POST
}
function insertPost($before, $offset, $after)
{
if(!empty($_POST[$offset])) {
return $before . $_POST[$offset] . $after;
}
return '';
}
$description = insertPost('a sentence', 'start', ' with something in the START.');
What I'm doing is, if I haven't got an ID in either $_POST or $_SESSION then redirecting. Preference is given to $_POST. So I have this:
$bool = 0;
if (isset($_POST['id'])) {
$bool = 1;
} elseif (isset($_SESSION['id'])) {
$bool = 1;
}
if (!$bool) {
...//redirect
}
Is there a quicker way to write this, APART from just removing the braces?
if(!( isset($_POST['id']) || isset($_SESSION['id']) ))
redirect();
(not sure if I understand how what's given to $_POST is preference).
You could just do:
$has_id = isset($_POST['id']) || isset($_SESSION['id']);
if (!$has_id) {
// redirect
}
(I'd recommend you to give your variables more descriptive names than just $bool.)
Although if you aren't using the variable for anything else, you could just do:
if (!isset($_POST['id']) && !isset($_SESSION['id'])) {
// redirect
}
if (isset($_POST['id']) || isset($_SESSION['id'])) {
$bool = 1;
}
This will do it, simples
$bool = (isset($_POST['id']) || isset($_SESSION['id'])) ? 1 : 0; // if isset, 1
($bool == 1?header(Location: www.whatever.com):null;
Using Conditional Operator, you can achieve this in one line statement
Example:
c = (a == b) ? d : e;