Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'd like to ask if this PHP/HTML code has any flaws which can be exploited by the potential aggressor:

<form method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<input type='text' name='foo' value='<?php echo htmlspecialchars($_POST['foo']); ?>' /> 
<input type='submit' value='bar' />

I'm aware that it can be exploited by calling script like this'><script>alert('xss')</script><foo' and

<?php echo $_SERVER['PHP_SELF']; ?>

should be replaced with

<?php echo htmlentities($_SERVER['PHP_SELF']); ?> or <?php echo htmlspecialshars($_SERVER['PHP_SELF']); ?>

Are there any other possible ways to conduct XSS attack on this piece of code? If so, how can I secure this form?

@Update: Ok, I've just found another possible attack - entering code like ' onmouseover='alert(String.fromCharCode(88,83,83,33)); (with the apostrophe in the beginning) into the text field, which causes simple 'XSS!' alert. It can be avoided by changing <?php echo htmlspecialchars($_POST['foo']); ?> to <?php echo str_replace('\'', '&#39;', htmlspecialchars($_POST['foo'])); ?>

share|improve this question
You've answered your own question... Though I think __FILE__ is the preferred way, rather than $_SERVER[ 'PHP_SELF' ] although I may be mistaken. Only other thing I can think to suggest is that you take a look at filter_input() for that post variable that you also never verified was set. – mseancole Jul 3 '12 at 15:50
Amendment: $_SERVER[ 'SCRIPT_NAME' ] is the preferred way, not __FILE__, not sure what I was thinking... Though the latter should work too. – mseancole Jul 3 '12 at 15:57
Could you write your edit as an answer and later accept it? It would help answerers. I'd upvote the answer too. – palacsint Jul 14 '12 at 17:40

For single-quoted attributes, use htmlspecialchars($text, ENT_QUOTES).

Depending on what this does, you might want to implement some sort of protection against CSRF attacks.

You might also want to check $_SERVER['SCRIPT_NAME'].

Other than that, this code seems reasonable.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.