0

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";
}
8
  • you can add a isset($_POST['your_submit_button']) Commented Feb 27, 2014 at 9:09
  • 1
    You just simply can check for if(isset($_POST['field_data'])) { echo 'ok'; } Commented Feb 27, 2014 at 9:09
  • isset does half the work !empty does :-) Commented Feb 27, 2014 at 9:11
  • But Attention: There is allways a way to fake an button click with javascript, you cant be sure that your user clicked on the submit button, allways keep this in your mind ;) Commented Feb 27, 2014 at 9:11
  • 1
    @ReeCube: oh, sure, sorry :-) Commented Feb 27, 2014 at 9:16

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

1

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

2 Comments

$_POST['submitted'] can throw an error if its not set ^^
hidden plain text field are easy to spoof.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.