shensw
shensw

Reputation: 233

How do I pass a session variable correctly?

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

Answers (3)

Giacomo1968
Giacomo1968

Reputation: 26056

A few things fixed here:

  • First you did not use a session_start() to actually retrieve $_SESSION values. Added here.
  • Next, you should check if the values are not empty by using !empty() in addition to isset(). Added here as well.
  • Finally, I recommend you use === 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

vitro
vitro

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

Raptor
Raptor

Reputation: 54212

You didn't add session_start() at the 1st line, thus the $_SESSION is empty.

Side Note:

  • You mixed up XHTML and HTML. xmlns is not required for HTML.
  • DOCTYPE is missing

Upvotes: 0

Related Questions