by Klaus Graefensteiner
19. February 2010 15:35
This is the first real thing I struggled with while learning PHP. I couldn’t make the form post to itself. Finally I managed to get it right. Here are two scripts that take a number as a string and post it back to the page. The examples that I searched and found on the web weren’t this helpful. So I decided to post my own scripts.
Self submitting form with GET
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<?php
$number= $_GET['number'];
?>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simple Self-Submitting Form</title>
</head>
<body>
<form method="GET" action="">
<label>Enter a number :</label>
<input type="text" name="number"></input>
<br />
<input type="submit" value="Submit">
</form>
<?php
if(count($_GET) > 0 && array_key_exists('number', $_GET))
{
echo $number;
}
?>
</body>
</html>
Self submitting form with POST
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<?php
$number= $_POST['number'];
?>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simple Self-Submitting Form</title>
</head>
<body>
<form method="POST" action="">
<label>Enter a number :</label>
<input type="text" name="number"></input>
<br />
<input type="submit" value="Submit">
</form>
<?php
if(count($_POST) > 0 && array_key_exists('number', $_POST))
{
echo $number;
}
?>
</body>
</html>
Download
You can download the two scripts here: SelfSubmittingPHPForms.zip
Ausblick
That’s it.