会话和cookie变量存储时没有特殊字符

时间:2013-09-16 16:39:31

标签: php session cookies

我将包含特殊字符的变量(例如@#$(用于描述一些))存储到会话和使用PHP的cookie中,但是当我检索它们时,我无法在存储的会话和cookie变量中看到特殊字符。提前谢谢。

                        //storing
                        $_SESSION['userid'] = $db_id;
            $_SESSION['email'] = $db_email;
            $_SESSION['password'] = $db_pass_str;
            setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
            setcookie("email", $db_email, strtotime( '+30 days' ), "/", "", "", TRUE);
            setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE); 

    //Retreivel
    if(isset($_SESSION["userid"]) && isset($_SESSION["email"]) && isset($_SESSION["password"]))
 {
    $log_id = preg_replace('#[^0-9]#', '', $_SESSION['userid']);
    $log_email = preg_replace('#[^a-z0-9]#i', '', $_SESSION['email']);
    $log_password = preg_replace('#[^a-z0-9]#i', '', $_SESSION['password']);
    // Verify the user`enter code here`

} 
else if(isset($_COOKIE["id"]) && isset($_COOKIE["email"]) && isset($_COOKIE["pass"]))
{
    $_SESSION['userid'] = $_COOKIE['id'];
    $_SESSION['email'] = $_COOKIE['email'];
    $_SESSION['password'] = $_COOKIE['pass'];
}

当我回显会话变量时,我没有看到我存储的特殊字符。 例如:我存储了test@example.com,但是当我查看时,我只能看到testexample.com。

1 个答案:

答案 0 :(得分:2)

使用htmlspecialchars对原始字符串进行编码。 例如,

<?php
$session_variable = "hello@World#$%@";
$new = htmlspecialchars("<?php echo $session_variable; ?>", ENT_QUOTES);
echo $new; // output: hello@World#$%@
?>