[php] Clearing _POST array fully

I want clear $_POST array content fully, all examples what I see in internet, looks like this:

if (count($_POST) > 0) {
    foreach ($_POST as $k=>$v) {
        unset($_POST[$k]);
    }
}

Tell please, this variant will be not more better? (Point of view as saving resources)

if (count($_POST) > 0) {
     $_POST = array();
}

or not ?

This question is related to php

The answer is


Yes, that is fine. $_POST is just another variable, except it has (super)global scope.

$_POST = array();

...will be quite enough. The loop is useless. It's probably best to keep it as an array rather than unset it, in case other files are attempting to read it and assuming it is an array.


You can use a combination of both unset() and initialization:

unset($_POST);
$_POST = array();

Or in a single statement:

unset($_POST) ? $_POST = array() : $_POST = array();

But what is the reason you want to do this?


The solutions so far don't work because the POST data is stored in the headers. A redirect solves this issue according this this post.

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?


To unset the $_POST variable, redeclare it as an empty array:

$_POST = array();

It may appear to be overly awkward, but you're probably better off unsetting one element at a time rather than the entire $_POST array. Here's why: If you're using object-oriented programming, you may have one class use $_POST['alpha'] and another class use $_POST['beta'], and if you unset the array after first use, it will void its use in other classes. To be safe and not shoot yourself in the foot, just drop in a little method that will unset the elements that you've just used: For example:

private function doUnset()
{
    unset($_POST['alpha']);
    unset($_POST['gamma']);
    unset($_POST['delta']);
    unset($_GET['eta']);
    unset($_GET['zeta']);
}

Just call the method and unset just those superglobal elements that have been passed to a variable or argument. Then, the other classes that may need a superglobal element can still use them.

However, you are wise to unset the superglobals as soon as they have been passed to an encapsulated object.


To answer "why" someone might use it, I was tempted to use it since I had the $_POST values stored after the page refresh or while going from one page to another. My sense tells me this is not a good practice, but it works nevertheless.