118

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!

eliwedel
  • 1,363
  • 2
  • 10
  • 12

15 Answers15

196
if( isset($_POST['fromPerson']) )
{
     $fromPerson = '+from%3A'.$_POST['fromPerson'];
     echo $fromPerson;
}
ehmad
  • 2,563
  • 4
  • 20
  • 19
73

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;
}
Molimo
  • 91
  • 1
  • 5
Dheeraj Bhaskar
  • 18,633
  • 9
  • 63
  • 66
  • 1
    As per Shi's comment [on Augustus Francis's answer](http://stackoverflow.com/a/18578542/199364), `empty()` is **not** correct for choice #1, because in php, the string `'0'` is equivalent to `false` - and `empty()` returns `true` for *all values equivalent to false*. So using `empty`, the code would skip printing if the value was `'0'`. If you want to exclude the empty string, see Augustus answer. – ToolmakerSteve Jan 08 '17 at 02:38
38

Surprised it has not been mentioned

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
John Magnolia
  • 16,769
  • 36
  • 159
  • 270
  • 2
    Why? If server method isn't POST, then the POST variable won't be set, so the second half is all that is needed. Am I wrong? – ToolmakerSteve Nov 04 '15 at 17:04
  • 2
    @ToolmakerSteve yes in most cases that is enough but not always my answer was to show another way it could be done. – John Magnolia Dec 13 '15 at 10:11
  • It will also work if you have a form with checkboxes and submit without a name. – John Magnolia Mar 06 '16 at 20:56
  • 2
    Describe a situation where `isset($_POST['fromPerson']` is `true`, even though `if($_SERVER['REQUEST_METHOD'] == 'POST'` is `false`. Unless there is such a situation, all that is needed is the `isset...` part. – ToolmakerSteve Jan 08 '17 at 02:13
  • True, but it's the other way around. `fromPerson` might not be present, but POST might still exist. The question was, "If $_POST exists." and only in an example, $_POST['fromPerson'] is used. In some situations, as [@goat describes here](https://stackoverflow.com/questions/2680160/how-can-i-tell-which-button-was-clicked-in-a-php-form-submit), even if `fromPerson` was a Submit name, it might not be present in POST. – papo Feb 10 '19 at 13:30
  • there are definately situations where you wanna check for server request method, but this is more an api thing, or when you wanna check wheter f.e. PUT was requested on the server and then drop the request ( if you want to forbid PUT ) -> for this question, it is unneccesary – clockw0rk Dec 06 '22 at 13:08
35

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.

takrl
  • 6,356
  • 3
  • 60
  • 69
Rafael
  • 393
  • 2
  • 6
  • 4
    empty() checks for variable existence and a non-empty value, so that's the function to use when an empty string should return false. – Han Dijk Jul 30 '13 at 13:11
  • 1
    @HanDijk - as per Shi's comment [on Augustus Francis's answer](http://stackoverflow.com/a/18578542/199364), `empty()` is **not** correct here, because in php, the string `'0'` is equivalent to `false` - and `empty()` returns `true` for *all values equivalent to false*. So using `empty`, the code would skip printing if the value was `'0'`. – ToolmakerSteve Jan 08 '17 at 02:23
  • imho it's always better to write a class that would acceppt all POST data and then check inside that class. you might try to strlen on each post field and catch the exception that would result when testing against NULL, and when strlen is actually 0, it's probably because the param was "" – clockw0rk Dec 06 '22 at 13:11
22
isset($_POST['fromPerson']) 
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
h3xStream
  • 6,293
  • 2
  • 47
  • 57
16

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.

Robert
  • 19,800
  • 5
  • 55
  • 85
  • Fantastic answer, except for the suggestion to use `empty`. As per Shi's comment [on Augustus Francis's answer](http://stackoverflow.com/a/18578542/199364), `empty()` is **not** correct as an alternative choice, because in php, the string `'0'` is equivalent to `false` - and `empty()` returns `true` for *all values equivalent to false*. So using `empty`, the code would skip printing if the value was `'0'`. If you want to exclude the empty string, see Augustus answer. – ToolmakerSteve Jan 08 '17 at 02:45
9
  • 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).
Bronek
  • 10,722
  • 2
  • 45
  • 46
  • This code only differs in behavior from the `isset` solution when the post field is set but contains NULL. This is a *good alternative*, *if* you want to allow `NULL` in the `else` branch. *However*, it is a mistake, if a string is needed; in that situation `isset` does the right thing, but this code does not - it will pass the `NULL` value on. [Robert's later answer](http://stackoverflow.com/a/36599270/199364) demonstrates the difference. – ToolmakerSteve Jan 08 '17 at 03:03
7

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);
linuxatico
  • 1,878
  • 30
  • 43
  • 1
    On the other hand, READABILITY of code is also important. IMHO, `isset` is a lot more readable than a filter expression. But thank you for pointing this out; it is a useful option to consider. – ToolmakerSteve Nov 04 '15 at 17:13
  • well, you can write your own myIsset/2 wrapper metod that uses filters but has the behaviour of isset/2 – linuxatico Nov 05 '15 at 08:28
  • "All the methods are actually discouraged" - that's a strong statement (even if NetBeans does mark as a warning). Do you have a link to an *authoritative source*, that *discourages* direct references to $_POST? (There is a *lot* about php that is designed for coding convenience rather than rigor - look at how many people in the answers to this question incorrectly use `empty`, tripped up by php's loose typing; its hard to imagine that accessing $_POST would be considered poor style.) – ToolmakerSteve Jan 08 '17 at 02:55
  • if you only need to know if it exists but you don't care about the value, for example, to check a submit button, you can use `filter_has_var(INPUT_POST, 'fromPerson')`. – PhoneixS Mar 31 '22 at 14:47
5

Try

if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
    echo "Cool";
}
user
  • 6,567
  • 18
  • 58
  • 85
Augustus Francis
  • 2,694
  • 4
  • 22
  • 32
4

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.

toshiro92
  • 1,287
  • 5
  • 28
  • 42
Jack Wright
  • 113
  • 2
  • 10
3

Try isset($_POST['fromPerson'])?

strager
  • 88,763
  • 26
  • 134
  • 176
3
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
    echo 'blah' . $_POST['fromPerson'];
}
jezmck
  • 1,138
  • 3
  • 18
  • 38
  • 1
    Does is_array($_POST) check if there are any values at all in POST? In my app I'm trying to determine if there was a post or not before doing anything else. – Jeff LaFay Feb 09 '11 at 02:49
  • 1
    See my edit. `is_array()` checks whether it's an array, the second part checks whether it has an item with the key `'fromPerson'`. – jezmck Feb 10 '11 at 09:07
2

if( isset($_POST['fromPerson']) ) is right.

You can use a function and return, better then directing echo.

Moslem Ben Dhaou
  • 6,897
  • 8
  • 62
  • 93
2

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;
Raymondim
  • 96
  • 3
  • 5
    `empty('0')` is `true`. So better not have `version` `0`, or `userID` `0`, etc. – Shi Jan 08 '17 at 01:55
-3

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
clockw0rk
  • 576
  • 5
  • 26
  • Why is this a class? Why are you unsafely accessing an array index without `isset` check? Why would this raise an exception? Why are you testing `$_POST` but are getting `$_GET`? Why are you `die`ing when catching the exception? This is like… all the worst possible practices rolled into one short snippet. – deceze Dec 06 '22 at 13:26
  • i already corrected the mistake. was posting an old version lol and the die("text") is just for debugging here. replace it with a return or standart value (or an exception object) – clockw0rk Dec 06 '22 at 13:29
  • That still leaves a lot of unaddressed criticism… – deceze Dec 06 '22 at 13:32
  • let me try and answere them: this is a class to keep hexagonal architecture and have a class whose domain is parsing of POST. i am unsafely accessing a post field with strlen to both check wheter it's set and if it holds a value. isset will just do about the same internally i guess – clockw0rk Dec 06 '22 at 13:35
  • But this will produce a notice and/or warning, which is what `isset` is there to prevent… – deceze Dec 06 '22 at 13:37
  • it is? i don't get any notice / warning. i have reporting turned on and looking through the symfony logs. only phpstorm tells me i should use `if($_POST[$pDate] !== '')` ... i'm sorry if i committed taboo by reimplementing isset here – clockw0rk Dec 06 '22 at 13:43