如何正确传递会话变量?

时间:2014-06-03 02:38:40

标签: php variables session

我是PHP的新手,我正在尝试使用此问题中提到的简单验证码 Numeric Captcha for PHP

我要做的是将$_SESSION['captcha']传递到我当前的页面,这样它就可以与我刚输入的输入进行比较,该输入应该通过“表单”传递。

这是我的代码:

<?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>

这样做的正确方法是什么?如何在当前代码中实现验证码?

3 个答案:

答案 0 :(得分:1)

这里解决了一些问题:

  • 首先,您没有使用session_start()来实际检索$_SESSION值。在这里添加。
  • 接下来,除了!empty()之外,您还应使用isset()检查值是否为空。这里也添加了。
  • 最后,我建议您使用===比较运算符而不是==。虽然==会检查值是否相同,但===会检查它们是否相同且数据类型相同。

这是清理过的代码:

<?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>

如果这仍然不适合你,你可以像这样转储$_POST$_SESSION的值,看看你得到了什么:

echo '<pre>';
print_r($_POST);
echo '</pre>';

echo '<pre>';
print_r($_SESSION);
echo '</pre>';

答案 1 :(得分:0)

您没有在第1行添加session_start(),因此$_SESSION为空。

旁注:

  • 您混淆了XHTML和HTML。 HTML不需要xmlns
  • 缺少DOCTYPE

答案 2 :(得分:0)

您需要使用

开始会话
session_start();

作为脚本输出之前的第一个调用。

请参阅文档:http://php.net/manual/en/function.session-start.php