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.

848 views
d

By. Jacob

Edited: 2019-11-03 04:34

PHP Article

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:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials