PHP: $_POST and $_GET is Always Defined
The PHP $_POST and $_GET super globals will never be undefined, developers should use empty instead of isset.
By. Jacob
Edited: 2019-11-03 04:34
Based on my testing, I recently found out that the $_POST and $_GET super globals is always defined when checked with isset().
By always defined, I mean that they exist, but they will be empty. So, if you must check them, you should use empty() instead of isset().
To understand what's happening, you can var_dump() the contents of the variables:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
var_dump($_POST);
var_dump($nothing);
Output:
array(0) { }
Notice: Undefined variable: nothing in /var/www/http_request_handler.php on line 10
NULL
As you can see, trying to output the $_POST variable gives us array(0) { }, while using the undefined $nothing variable results in a undefined variable notice.
Note. to check the request method, read this tutorial: Checking the Request Method
Check if $_POST and $_GET is empty
As I mentioned, $_POST and $_GET will always be defined, so we should check them using empty() instead of isset(). To do this, we can use an if statement:
if (empty($_POST)) {
echo '$_POST was empty.';
}
Tell us what you think: