PHP Form Helper – Submit Listener

By  on  

Unfortunately for me, web forms a big part of my day. It's not that web forms are difficult, it's that they're so damn time consuming. Validation, formatting, and processing are a must for web forms and the redundancy that goes into performing the task over and over is enough to drive a developer crazy.

The trigger to the form validation and subsequent processing is form submission. How do you know when a form has been submitted? At the top of the PHP script, before any output, you code:

if(isset($_POST['submit'])) {
	//validation here

	//conditional processing here

}

What if there's also a "cancel" button? You'd code:

if(isset($_POST['submit'])) {
	//validation here

	//conditional processing here
}
elseif(isset($_POST['cancel'])) {
	//redirect somewhere<
}

The above isn't good enough for me. I create too many forms to continue the isset() muck. Also, what about the "_x" browser quirk for when you have an image submit button (e.g. instead of PHP reading in "submit", it reads in "submit_x")? What about maintainability? I've created a function to handle all form submission situations that works great for my purposes.

The Code

function submit($trigger = 'submit') {
	return (isset($_POST[$trigger]) || isset($_POST[$trigger.'_x']) || isset($_GET[$trigger]) || isset($_GET[$trigger.'_x']));
}

The Usage

if(submit()) {
	//submit button pressed
}
elseif(submit('cancel')) {
	//cancel button pressed
}

The Explanation

There's one optional argument to send to the function: $trigger. $trigger represents the name of the button you expect to be pressed -- default being "submit." If one of the buttons is pressed, the selected processing is run; if not, no processing is run.

Do you have a function you use? If so, please share.

Recent Features

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Incredible Demos

Discussion

  1. chuck

    David,

    This is a great little function to make tedious tasks less so.

    Thanks,
    Chuck

  2. JGM

    I typically use something like:

    if (eregi('post',$_SERVER['REQUEST_METHOD'])) {
    // handle form processing here
    }
    

    to detect a form submission.

  3. With this implementation you loose the submit scope, which you should not want. I can call this type of implementation with something like form.php?submit_x=foobar that triggers the execution, but the form normally uses post. This is the same as using the super global $_REQUEST as form context.

  4. josh

    I generally use a hidden form token tied to the users session to help prevent CSRF and multiple form submissions. You can then check for the form token.

  5. Hi!

    In my opinion josh`s and JGM`s approach are the best ones: you can change names of your form fields, and by sure that your form processor correctly catches submitted data.

    JGM: it`s better to use stripos() or to check whether the $_POST global variable contains any data (count($_POST)>0).

    Regards

  6. I’m a little confused as to the real reason to develop in this method. It seems that you’re either:
    1) developing all your display and processing in one page
    or
    2) not handling someone surfing directly to your posting script transparently in an already proven way

    This is the method that I use:
    post.php
    — has the form, the tokens embedded
    — posts to post.process.php

    post.process.php
    — checks for embedded token – if not, redirects back to post.php
    — has an array of expected – whitelisted data. Checks post variables for all of them in a loop, scrubbing them, and putting them into a clean array
    — check clean array for required things. If good, continue, if bad, store error and redirect back to post.php
    — after process, redirect to post.success.php (if necessary, post.success could check some sort of session information ot make sure you came from post.process.php… .not always necessary)

    What user sees:
    post.php to post.success.php (redirect is usually transparent to user, not to browser, however) on success.
    post.php to post.php on error.

    what happens if:
    user surfs to post.process.php? – redirect to post.php because first check is for the CSRF token – very little overhead and a good method to remember to stay secure
    user surfs to post.success.php? – might show success message (that is if you haven’t set a session variable to redirect them away) but with no real action.

    I hope this helps…

    If I’m missing something about your reason for implementation, please let me know. thanks! :)

  7. Thanks for sharing Aaron.

    I do all the post processing and form/display on one page. It’s much easier to put existing form values into place when there is an error (instead of making them type their valid values back in).

  8. Do you clean all of the posted information first before repopulating the page? It could be possible for them to insert a custom type of error into one of the forms, which might error out, and then put content into your page…. think:

    What if they put:
    ” />

  9. Ahh! It chopped off the rest of my example…. :( (I showed an xss example… maybe thats why)

    Basically in summary – I was just saying that make sure you do clean your input before you redisplay… otherwise you could get xss – but I’m assuming you’re already doing this. In my method, I store the whiteListed data in a session – and programatically(if thats a word) fill up a $values array on my form page again.

    Anyways – thanks David for responding – feel free to stop by my blog and leave long winded responses like I’ve done to you! sorry! :)
    -aaron

  10. Great function .. Works like a charm. I did some little modification but it is not worth showing here .. But thanks anyway for your great help.

  11. René Monroy

    Talking about forms, I’m using mootools to request a php page which I want to have the isset function but… did you notice that elements can´t be handled by isset through ajax by post method? Nevertheless, It seems to be good with get method, well almost, first input disappears to me :S

    Maybe it’s something in my JavaScript function, but without the isset there’s no failures, what do you think David, am I wrong or something?

  12. @René: I’ve not noticed that. I do know that if a value is empty that MooTools may strip the entire variable out of the POST. Are you sure the form field is being populated?

  13. René Monroy

    As expected, it wasn’t the script, htaccess ‘rewriterule’ was causing some conflicts and it’s ok now.

    By the way, thanks for the additional info,

    Regards

  14. cxcxcx32323232

    dsf dsfdsfsdf fdsfsdf

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!