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()
Related
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.
I was writing in PHP and making so the page was declared by get method. For an example if it were index.php?page=home it would take home and compare to other strings and... ya include the home BUT the compression in the if statement dosnt work... I have also write that if get method == start then dont show the side news but it still showed it!
Here's my code:
if(isset($_GET['page']) && $_GET['page'] == 'start'){
$adbool = false;
}else{
include('inc/main.php');
}
And here is the if statement for deleting side news:
if(isset($adbool) && !$adbool == false){
include('inc/ad.php');
}
and remember this !$adbool == false is not equal to this $adbool != false
You better understand this part as well !$adbool == false;
!$adbool means that $adbool is equal to false;
so !$adbool == false; means if false=false hence this condition always set to to true.
Thats why your logic is failing
Change this
if(isset($adbool) && !$adbool == false){
include('inc/ad.php');
}
To this
if($adbool == TRUE){//simply check weather its set to to true or not
include('inc/ad.php');
}
use
if(isset($adbool) && $adbool){
include('inc/ad.php');
}
this will check if $adbool is set, and if it's set to true.
My code as follows:
if($_POST['user_id'] = ''){
//some statement;
}
In the above if condition I have put only single =. PHP is not showing any error but I am getting a white blank page. Does anyone has any clue?
if($_POST['user_id'] = '') means:
$_POST['user_id'] becomes '' .. if ('') // always false
if($_POST['user_id'] == '') means:
$_POST['user_id'] compares to '' .. if ( comparison)
Not sure if trolling or real question...
you said it yourself, you're using a single =. You need 2 to check for equality.
if($_POST['user_id'] == ''){
//some statement;
}
When you use a single equal sign, you're basically "set $_POST['user_id'] to '', then test if it's true). Since '' evaluates to false, you get nothing.
This:
if($_POST['user_id'] = ''){
Tries to assign an empty string to $_POST['user_id']. This:
if($_POST['user_id'] == ''){
Is a comparison. You should almost always be doing the second one - the first one over-rides the value in $_POST, and returns the value of the assignment.
try it
Use it
$user_id = $_POST['user_id'];
if($user_id == ''){
//some statement;
}
inseted of
if($user_id = ''){
//some statement;
}
Or try another one
$user_id = $_POST['user_id'];
if(isset($user_id) && !empty($user_id)){
//some statement;
}
It's not triggering any error because it is a valid condition.
if($_POST['user_id'] = '')
equals to
$_POST['user_id'] = '';
if($_POST['user_id']){
//Boolean comparison of a string. Empty = false. Not empty = true.
}
An example of use:
function division($var1, $var2){
if($var2 > 0){
return $var1/$var2;
return false;
}
if($result = division(50,2)){
//It returned 25 which is true!
}
if(!$result = division(50,0)){
//Returned FALSE because you can't divide by zero!
}
I've been writing my "If this variable is not empty" statements like so:
if ($var != '') {
// Yup
}
But I've asked if this is correct, it hasn't caused a problem for me. Here is the answer I found online:
if (!($error == NULL)) {
/// Yup
}
This actually looks longer than my approach, but is it better? If so, why?
Rather than:
if (!($error == NULL))
Simply do:
if ($error)
One would think that the first is more clear, but it's actually more misleading. Here's why:
$error = null;
if (!($error == NULL)) {
echo 'not null';
}
This works as expected. However, the next five values will have the same and (to many, unexpected) behavior:
$error = 0;
$error = array();
$error = false;
$error = '';
$error = 0.0;
The second conditional if ($error) makes it more clear that type casting is involved.
If the programmer wanted to require that the value actually be NULL, he should have used a strict comparison, i.e., if ($error !== NULL)
It is good to know exactly what is in your variable, especially if you are checking for uninitialized vs null or na vs true or false vs empty or 0.
Therefore, as mentioned by webbiedave, if checking for null, use
$error !== null
$error === null
is_null($error)
if checking for initilized, as shibly said
isset($var)
if checking for true or false, or 0, or empty string
$var === true
$var === 0
$var === ""
I only use empty for ''s and nulls since string functions tend to be inconsistent. If checking for empty
empty($var)
$var // in a boolean context
// This does the same as above, but is less clear because you are
// casting to false, which has the same values has empty, but perhaps
// may not one day. It is also easier to search for bugs where you
// meant to use ===
$var == false
If semantically uninitialized is the same as one of the values above, then initialize the variable at the beginning to that value.
$var = ''
... //some code
if ($var === '') blah blah.
Why just don't
if (!$var)
There are ways:
<?php
error_reporting(E_ALL);
$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));
?>
Another:
<?php
$var = '';
// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
echo "This var is set so I will print.";
}
?>
To check if it's empty:
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>
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.