简体   繁体   中英

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?

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>';

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM