Security Images with PHP and ImageMagick - The Form (
Page 3 of 4 )
Our form is much simpler and has very little PHP code in it. It starts out quite simply and in similar fashion to the securityimage.php script except that this page is sending HTML output to the browser so we have the usual HTML up top.
<?php
ob_start();
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Secure Images Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
Once that's done, we can define our form function. Putting the form in a function allows us to call it selectively rather than showing the form again even after successful submittal (as was the case in the original article). The function is simple and contains a minimal form:
<?php
function Form() {
?>
<form method="post">
Please sign up for our website:<br /><br />
Your Name: <input name="name" type="text" size="25" /> <br /><br />
<img alt="Security Image" src="securityimage.php" /><br/ ><br/ >
Enter what you see: <input name="securityImageValue" type="text" size="15" /><br /><br />
<input type="submit" name="Submit" value="Signup!" />
</form>
<?php
}
The most notable part of the form itself is that the image points directly to the securityimage.php script. Remember, the securityimage.php script sends an image directly back to the browser, no HTML, so this works just fine. Next we will define our form handler.
if (isset($_POST['securityImageValue']) && isset($_SESSION['strSec'])) {
if (md5($_POST['securityImageValue']) == $_SESSION['strSec']) {
print 'You correctly enetered the security image text. Goody for you.';
}
else {
print 'The text you entered does not match the security image you saw. Please try again.<br /><br />';
Form();
}
}
else
Form();
This bit of code tests to see if the form has been submitted by checking to see if we have a security string hash in our session and if we have submitted a guess at the contents of the security string. If those two conditions prove to be false, we show the form. If they are met, we process the form. We take the md5 hash of the value entered by our user and compare it to the value we stored in their session. If they match, then the user entered the text from the security string correctly. If they do not match, then the wrong text was entered and we need to tell the user and show the form again. This could be made more sophisticated by only allowing a certain number of attempts by a user, but is not necessary, as the security image itself prevents automated signup on it's own. The last few lines of code just close our HTML and flush our output buffer.
?>
</body>
</html>
<?php
ob_end_flush();
?>