PHP表单提交和表单数据验证

PHP表单提交和表单数据验证

问题描述:

In PHP is this enough to guarantee a form has been submitted by clicking the form submit button and to verify the content posted is not empty?

if($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['field_data']))
{
echo "ok";
}

在PHP中,这足以保证通过单击表单提交按钮提交表单并验证发布的内容 是不是空? p>

  if($ _ SERVER ['REQUEST_METHOD'] =='POST'&&!empty($ _ POST ['field_data']))
  {
echo“ok”; 
} 
  code>  pre> 
  div>

I think, there may be a way to be sure the form was submitted using your form.
If I would like to do it, I think I will make something like this :

$secure = $_SESSION['form']['submit'] = MD5(time());
<form>
<input type='hidden' name='secure_form' value='<?php echo $secure ?>' />
</form>

And else when submitted check the value :

if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['secure_form']) && $_SESSION['form']['submit'] ==  $_POST['secure_form']) {
  //do stuff
}

Of course, you have to add session_start() at the top of the page!

I tend to use a hidden form field

<?php
$csrf_token  = md5(time().'random string');

$_SESSION['csrf'] = $csrf_token;

?>
<input type="hidden" id="submitted" name="submitted" value="yes"/>
<input type="hidden" id="csrf" name="csrf" value="<?php echo $csrf_token; ?>"/>

Then in my PHP I'd use something like:

if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['submitted'] == 'yes' && $_POST['csrf'] == $_SESSION['csrf']){
   // Do something
   echo 'Form submitted via POST';
}

Updated to include a CSRF field

first you need to check $_SERVER['REQUEST_METHOD'] output so best way to convert output in upper

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

Then you can check with submit button name also like

<input type="hidden" id="submitted" name="submitted" value="yes"/>

if(strtoupper($_SERVER['REQUEST_METHOD'])=='POST'  && isset($_POST['submitted']) && $_POST['submitted'] == 'yes'){

also you can check all values of form which will be submitting by isset() or empty()