我是 PHP 新手,在登录页面上苦苦挣扎。我有以下“有效”的脚本,但现在我想设置一个会话,如果用户的密码正确,我可以转移到其他页面。所以我试图弄清楚其他页面上需要什么来检查会话。
从这里开始,如果我在我回来的页面上放这样的东西:
<?php
if($_SESSION['login'] = "1") {
echo "you are logged in";
}
else
{
echo "you are not logged in";
}
?>
似乎我一直收到我的成功信息。我一定不明白这是如何工作的。任何建议表示赞赏——如果我需要的话,我愿意完全重写这个。谢谢!
这是我当前的登录脚本:
<?php
// error reporting
ini_set('display_errors',1);
error_reporting(E_ALL);
$host="foo"; // Host name
$username="foo"; // Mysql username
$password="foo"; // Mysql password
$db_name="foo"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1) {
session_start();
$_SESSION['login'] = "1";
header ("Location: http://www.google.com");
}
else {
session_start();
$_SESSION['login'] = '';
header ("Location: http://www.yahoo.com");
}
?>
应用下面建议的更改,我在返回的页面中有以下内容:
<?php
session_start();
if ($_SESSION['login'] == "1") {
echo "you are logged in";
}
else if ($_SESSION['login'] == "")
{
echo "you are not logged in";
}
?>
以及对我的登录脚本的以下更改:
if($count==1) {
session_start();
$_SESSION['login'] =="1";
header ("Location: login.php");
}
else {
session_start();
$_SESSION['login'] == "";
header ("Location: login.php");
}
现在无论如何,我都会收到“您尚未登录”的消息……嗯。
更新——好的——如果我不对我的脚本进行 == 更改,它似乎可以工作。如果我有
if($count==1) {
session_start();
$_SESSION['login'] = "1";
header ("Location: login.php");
}
else {
session_start();
$_SESSION['login'] = "";
header ("Location: login.php");
}
这在我回到的页面中:
<?php
session_start();
if ($_SESSION['login'] == "1") {
echo "you are logged in";
}
else if ($_SESSION['login'] == "")
{
echo "you are not logged in";
?>
......这似乎工作。