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.

900 views
d

By. Jacob

Jacob Kristensen (Turbulentarius) is a Web Developer based in Denmark. He is currently pursuing a Bachelor's degree in Web Development at Zealand, focusing on learning React and refining his existing skills.

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. How to use the AVIF image format in PHP; A1 or AVIF is a new image format that offers better compression than WebP, JPEG and PNG, and that already works in Google Chrome.
  2. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  3. How to create a router in PHP to handle different request types, paths, and request parameters.
  4. Tutorial on how to use proxy servers with cURL and PHP
  5. 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.

More in: PHP Tutorials