Web Development for 2010

Alexander Dickson - Web Developer covering PHP, jQuery / Javascript, XHTML, CSS, more

Form security - submitting forms to themselves in PHP

Published on Wednesday, 3rd March 2010.

Often, well in fact for me nearly always, you want a form to submit to the page it is on. Here is some standard markup (with some PHP).

<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>" method="post" > <fieldset> <legend>Contact Me</legend> <label for="email">Email:</label> <input type="text" name="email" id="email" /> <button type="submit">Submit</button> </fieldset> </form>

I've always added the htmlspecialchars() so that if anything fishy is appended to the URL, it will be encoded safely.

However, I've been experimenting with omitting htmlspecialchars() and it still seems to be safe, because the browser is encoding characters from the URL. For example accessing form.php?hack=" onsubmit="alert('xss') will make the form's action attribute /things/?hack=%22%20onsubmit=%22alert(%27xss%27). Not elegant, but not dangerous either (I think).

So is it necessary to use htmlspecialchars() ? I still will, and I recommend you do too. It takes 4 seconds to implement, and it will safeguard you against any client that does not automatically encode the special characters in the URL.

Comments

  • Alexander Dickson

    Posted on Thursday, 4th March 2010 @ 12:59am.

    @nickf Ah yes, I remember your Stack Overflow question about that. IIRC, the solution was to make the attribute just a simple question mark (?).

    Like CakePHP, Kohana has a similar method, <?php echo form::open(); ?>.

  • nickf

    Posted on Thursday, 4th March 2010 @ 12:54am.

    I would generally just leave the action attribute blank and it posts back to itself. Except then I found that some browser (Safari? Opera?) didn't like that at all, so I switched to using an empty attribute (action=""), and that was all good until a different browser (I think Chrome?) didn't like that either. I kinda forget what I ended up using in the end: I've been using CakePHP for 6 months now and leave it all up to that.

Leave a Comment

Comment Details

Your email will never be displayed. If you have a gravatar, it will be displayed.

Note: Your comment may require approval before it is posted to the site.

Stack Overflow Profile

view full profile »

About

I'm a web developer from the Sunshine Coast, Australia. more »