Checking if form has been submitted - PHP

2019-01-03 01:31发布

What is the best way of checking whether or not a form has been submitted to determine whether I should pass the form's variables to my validation class?

First I thought maybe:

isset($_POST)

But that will always return true as a superglobal is defined everywhere. I don't want to have to iterate through each element of my form with:

if(isset($_POST['element1']) || isset($_POST['element2']) || isset(...etc

Whilst writing this question I thought of a much more basic solution, add a hidden field to act as a flag that I can check.

Is there a 'cleaner' way to do it than adding my own flag?

8条回答
孤傲高冷的网名
2楼-- · 2019-01-03 01:59

For general check if there was a POST action use:

if (!empty($_POST))

EDIT: As stated in the comments, this method won't work for in some cases (e.g. with check boxes and button without a name). You really should use:

if ($_SERVER['REQUEST_METHOD'] == 'POST')
查看更多
不美不萌又怎样
3楼-- · 2019-01-03 01:59

I had the same problem - also make sure you add name="" in the input button. Well, that fix worked for me.

if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['add'])){
    echo "stuff is happening now";
}

<input type="submit" name="add" value="Submit">
查看更多
男人必须洒脱
4楼-- · 2019-01-03 02:06

Try this

 <form action="" method="POST" id="formaddtask">
      Add Task: <input type="text"name="newtaskname" />
      <input type="submit" value="Submit"/>
 </form>

    //Check if the form is submitted
    if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['newtaskname'])){

    }
查看更多
贪生不怕死
5楼-- · 2019-01-03 02:10

Actually, the submit button already performs this function.

Try in the FORM:

<form method="post">
<input type="submit" name="treasure" value="go!">
</form>

Then in the PHP handler:

if (isset($_POST['treasure'])){
echo "treasure will be set if the form has been submitted (to TRUE, I believe)";
}
查看更多
可以哭但决不认输i
6楼-- · 2019-01-03 02:13

How about

if($_SERVER['REQUEST_METHOD'] == 'POST')
查看更多
不美不萌又怎样
7楼-- · 2019-01-03 02:15

Use

if(isset($_POST['submit'])) // name of your submit button
查看更多
登录 后发表回答