将php变量从this.php传递给that.php

时间:2014-03-05 15:50:43

标签: php html5 web-services variables

所以我需要将一个变量从一个php传递到另一个php页面,但我不知道该怎么做。我得到了这段代码“$ realname = $ row ['name'];”存储该人的真实姓名,以便在他们成功登录后在另一个页面中显示它,但是当我尝试在另一个页面中使用$ realname变量时,它不会显示它。我该如何制作这个有效的???提前谢谢

第一页login.php

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php

include 'functions.php';

if(loggedin())
{
header("Location: userarea.php");
exit();
}

if(isset($_POST['login']))
{
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];

    //validate
    if($username&&$password)
    {
        $login = mysql_query("SELECT * FROM users WHERE username='$username'");
        if(mysql_num_rows($login) == 1)
        {
            while($row = mysql_fetch_assoc($login))
            {

                $db_password = $row['password'];
                if($password == $db_password)
                   $loginok= TRUE;
                else
                   $loginok = FALSE;

                 if($loginok==TRUE)
                 { 

                                  $realname= $row['name'];

                                       if($rememberme == "on")
                        setcookie("username", $username, time() + 7200);
                    else if ($rememberme == "")
                        $_SESSION['username'] = $username;


                    header("Location: userarea.php");
                    exit();
                 }
                 else
                     die("Incorrect username or password. Please try again or contact your local admin.");
            }

        }die("Incorrect username or password. Please try again or contact your local admin.gdfgdfgdfg");
    }
    else
        die("Please enter a username and password.");

}

?>


<h>Welcome!</h>

    <form action="login.php" method="POST">

    Username:<br /> 
    <input type="text" name="username"><p />

    Password:<br /> 
    <input type="password" name="password"><p /  >  



    <input type="checkbox" name="rememberme"> Remember me<br />

    <input type="submit" name="login" value="Log in">

    </form>

</body>
</html> 

Page 2 userarea.php(你可以看到我声明了$ realname变量,但我无法使用它)

<html>
<body>

<?php

include 'functions.php';


if(!loggedin())
{
header("Location: login.php");
exit();

}

echo "Hello $realname";

?>



<h>Access Granted! Yeiy! </h>
<a href="logout.php"> Log out </a>


</body>
</html>

2 个答案:

答案 0 :(得分:0)

这正是sessions的用途:

  

会话是针对单个会话ID为各个用户存储数据的简单方法。这可用于在页面请求之间保留状态信息。会话ID通常通过会话cookie发送到浏览器,ID用于检索现有会话数据。

第一页login.php

<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
$_SESSION['realname'] = $row['name'];

Page 2 userarea.php

<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
echo "Hello $_SESSION['realname']";

答案 1 :(得分:0)

首先在登录页面上传递$_SESSION['var_name'];然后

在userarea页面的顶部启动session_start()并回显您的会话变量

echo $_SESSION['var_name'];