Lisa Miskovsky
Lisa Miskovsky

Reputation: 926

How to detect if $_POST is set?

I want to know how to detect if $_POST is set or not.

Right now I detect it like this:

if(isset($_POST['value']))

But I'm not looking if value is set anymore. Basically, any POST will work.

if(isset($_POST))

I'm not sure how PHP handle this. Perhabs isset($_POST) is always returns true since it's a PHP global?

Basically, how can I do this?

Upvotes: 30

Views: 69791

Answers (6)

Baker Hasan
Baker Hasan

Reputation: 374

Best way to check $_POST

<?php 
if(count($_POST)){}

Upvotes: -1

Spencer Mark
Spencer Mark

Reputation: 5311

I know this answer has already been answered, but here's a simple method I'm using in one of my classes to figure whether the post has been set (perhaps someone will find it useful):

public function isPost($key = null) {

    if ($_SERVER['REQUEST_METHOD'] != 'POST') {

        return false;

    }

    if (!empty($key)) {

        return isset($_POST[$key]);

    }

    return true;

}

Upvotes: 2

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

Just use it as below. because its super global so its always return true when checking for isset and empty.

<?php
    if($_POST)
    {
        echo "yes";
    }
?>

Upvotes: 4

Salman Arshad
Salman Arshad

Reputation: 272296

$_POST is an array. You can check:

count($_POST)

If it is greater than zero that means some values were posted.

Upvotes: 14

niaccurshi
niaccurshi

Reputation: 1295

A simple solution may well be to just use

if (!empty($_POST))

Upvotes: 4

hsz
hsz

Reputation: 152286

Try with:

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {}

to check if your script was POSTed.

If additional data was passed, $_POST will not be empty, otherwise it will.

You can use empty method to check if it contains data.

if ( !empty($_POST) ) {}

Upvotes: 64

Related Questions