How do I make a PHP form that submits to self?
The proper way would be to use $_SERVER["PHP_SELF"]
(in conjunction with htmlspecialchars
to avoid possible exploits). You can also just skip the action=
part empty, which is not W3C valid, but currently works in most (all?) browsers - the default is to submit to self if it's empty.
Here is an example form that takes a name and email, and then displays the values you have entered upon submit:
<?php if (!empty($_POST)): ?>
Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br>
Your email is <?php echo htmlspecialchars($_POST["email"]); ?>.<br>
<?php else: ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit">
</form>
<?php endif; ?>
I guess , you means $_SERVER['PHP_SELF']
. And if so , you really shouldn't use it without sanitizing it first. This leaves you open to XSS attacks.
The if(isset($_POST['submit']))
condition should be above all the HTML output, and should contain a header()
function with a redirect to current page again (only now , with some nice notice that "emails has been sent" .. or something ). For that you will have to use $_SESSION
or $_COOKIE
.
And please. Stop using $_REQUEST
. It too poses a security threat.
That will only work if register_globals
is on, and it should never be on (unless of course you are defining that variable somewhere else).
Try setting the form
's action
attribute to ?
...
<form method="post" action="?">
...
</form>
You can also set it to be blank (""
), but older WebKit versions had a bug.
Try this
<form method="post" id="reg" name="reg" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"
Works well :)