Reputation: 233
I'm really new to PHP, and I'm trying to use the simple captcha mentioned in this question Numeric Captcha for PHP
What I'm trying to do is pass the $_SESSION['captcha']
to my current page, so it can compare with the input I just entered which is supposed to pass by the "form".
Here's my code:
<?php
if(isset($_POST['captcha'] ,$_SESSION['captcha'])) {
if ($_POST['captcha'] == $_SESSION['captcha'])
echo 'YES, YOU DID IT';
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>captcha test</title>
</head>
<body>
<form name="input" action="index.php" method="POST">
<img src="captcha.php">
Enter the code above: <input type="text" name="captcha">
<input type="submit" value="Submit">
</form>
</body>
</html>
What's the correct way to do this? How can I implement the captcha in my current code?
Upvotes: 1
Views: 143
Reputation: 26056
A few things fixed here:
session_start()
to actually retrieve $_SESSION
values. Added here.!empty()
in addition to isset()
. Added here as well.===
comparison operator instead of ==
. While ==
will check if values are the same, ===
will check if they are the same and the same data type.Here is the cleaned up code:
<?php
session_start();
if (isset($_POST['captcha'], $_SESSION['captcha']) &&
!empty($_POST['captcha']) && !empty($_SESSION['captcha'])) {
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo 'YES, YOU DID IT';
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>captcha test</title>
</head>
<body>
<form name="input" action="index.php" method="POST">
<img src="captcha.php">
Enter the code above: <input type="text" name="captcha">
<input type="submit" value="Submit">
</form>
</body>
</html>
If this still does not work for you, you can dump the values of $_POST
and $_SESSION
like this to see what you are getting:
echo '<pre>';
print_r($_POST);
echo '</pre>';
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
Upvotes: 1
Reputation: 939
You need to start your session with
session_start();
as a first call before your script has any output.
See documentation: http://php.net/manual/en/function.session-start.php
Upvotes: 0
Reputation: 54212
You didn't add session_start()
at the 1st line, thus the $_SESSION
is empty.
Side Note:
xmlns
is not required for HTML.Upvotes: 0