2013-01-16 22 views
1

如何使用登录使用2文件设置会话?首页>登录>首页
我在代码中做错了什么? 谢谢。如何使用登录使用2文件设置会话?主页>登录>首页

home.php

<?php 
    session_start(); 
?> 
<!DOCTYPE html> 
<html><head><title></title></head> 
<body> 
<?php 
    if($_SESSION['account']){ 
     print"login successful"; 
     //do something 
    } 
    else{ 
     print"login invalid"; 
     print" 
      <form method=\"post\" action=\"login.php\"> 
       account: <input type=\"text\" name=\"account\"><br> 
       password: <input type=\"text\" name=\"password\"><br> 
       <input type=\"submit\" value=\"login\"> 
      </form> 
     "; 
    } 
?> 
</body> 
</html> 

的login.php

$account = mysql_escape_string($_POST['account']); 
$password = mysql_real_escape_string($_POST['password']); 
if($account == 'myaccount' && $password == 'mypassword'){ 
    session_start(); 
    $_SESSION['account'] = $account; 
    $_SESSION['password']; 
    print"<meta http-equiv=\"refresh\" content=\"0;url=home.php\">"; 
    header("location: home.php"); 
    exit(); 
} 
else{ 
    print"<meta http-equiv=\"refresh\" content=\"0;url=home.php\">"; 
    header("location: home.php"); 
    exit(); 
} 

回答

1

您还没有存储$_SESSION阵列上的任何数据。

尝试:

$_SESSION['account'] = true; // Or something else that evaluates to true and is relevant. 
$_SESSION['password'] = 'please, anything but your password plaintext. think of the children'; 

这样,当你测试的登录操作上home.php结果:

if($_SESSION['account']){ 
    print"login successful"; 
    //do something 
} 

你能满足的条件。

+0

感谢答复,但之后,我提出,它仍然会显示invaild(在else),我不明白为什么? – user1775888

+0

尝试在login.php中删除'print',并且只留下'header()'。无论哪种方式,标题将在响应开始时发送,因此,除非您正在缓冲,否则在输出任何内容后调用'header()'将成为无操作。 –

1

基于脚本的:

$_SESSION['account']; 
$_SESSION['password']; 

应该是这样的:

$_SESSION['account'] = $account; 
$_SESSION['password'] = $password; 

但请注意,请不要在生产现场使用。这不会对用户进行身份验证。

您不能将会话用作登录某人的唯一方法,并且要求他们登录。会话很容易被劫持。良好的用户认证系统:

加密密码

数据库

存储的用户信息

收集用户信息,并设置

现在让用户登录,每次访问时间一个新的页面,您将使用seesion id,passsword,用户ip和会话变量来验证用户并允许他们查看页面。基本上你会创建一个函数或类以安全的方式处理这个问题。

现在对于那些刚开始学习php的人来说,已经有很多很棒的登录脚本了。任何对用户进行身份验证的好网站都是从一个非常好的用户身份验证系统开始,然后在其中建立一个网站。

+0

这不会对用户进行身份验证。 – user1775888

0

变线:

if($_SESSION['account']){ 
    print"login successful"; 
} 

通过

if(isset($_SESSION['account']) && $_SESSION['account'] == true){ 
    print"login successful"; 
}