在 html 中显示一个 php cookie

Display a php cookie in html

本文关键字:一个 php cookie html 显示      更新时间:2023-09-26

我用php设置了一个cookie。这是我的代码:

<?php
include_once 'php/config.php';
session_start();   //starting the session for user profile page
if(!empty($_POST['username']))   //checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
    $username = mysql_real_escape_string($_POST['username']);
    $password = mysql_real_escape_string($_POST['password']);
    $query = mysql_query("SELECT * FROM users where username = '$username' AND password = '$password'") or die(mysql_error());
    $row = mysql_num_rows($query) or die(mysql_error());
    if($row==1)
    {
        $_SESSION['username'] = $username;
        setcookie('username', $username, time() + (86400 * 30), "/"); // 86400 = 1 day
        echo $_SESSION['username'];
        echo "SUCCESSFULLY LOGGEDIN...";
    echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
    }
    else
    {
        echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
            echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
    }
}
?>

我想在 html 中显示"用户名"cookie,例如 Hi ".请帮忙。

尝试了这个JavaScript:

<script type="text/javascript">
  function getCookie(name)
  {
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return (value != null) ? unescape(value[1]) : null;
  }
</script>

使用 echo $_COOKIE['username']; 而不是 echo $_SESSION['username']; 。它将在页面的第二次重新加载中回显。(为什么?

<span id="myId"><span>
<script>
document.getElementById('myId').innerHTML=listCookies()
function listCookies() {
    var theCookies = document.cookie.split(';');
    var aString = '';
    for (var i = 1 ; i <= theCookies.length; i++) {
        aString += i + ' ' + theCookies[i-1] + "'n";
}
    return aString;
}
</script>