下面是以下腳本,第一個腳本是checklogin.php。這匹配存儲在MYSQL數據庫中的用戶名和密碼。一旦檢查到這些信息,他們將通過使用重定向功能發送到他們的個人頁面。
最底層的php腳本是user1的登錄頁面。我想在那裏確認此人已正確登錄並無權查看此頁面。
此刻,當我以user1身份登錄時,顯示頁面3.php,即它說我沒有正確登錄。我知道我需要設置一個會話,如: $ _SESSION [logged in'] =='y'; ,我認爲這應該去的地方密碼正在比較存儲在數據庫中。目前,我無法輸入我的登錄信息,最後直接輸入正確的文件。任何幫助都感激不盡。
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root", "root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if ($exists > 0) {
//IF there are no returning rows or no existing username
//$_SESSION['logged in'] == 'y';
while ($row = mysql_fetch_assoc($query)) {
//display all rows from query
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if (($username == $table_users) && ($password == $table_password)) {
// checks if there are any matching fields
if ($password == $table_password) {
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
$_SESSION['logged_in'] = 'y';
//echo $table_id;
//echo $page_id;
redirect($page_id); //take the user to the page specified in the users table
} else {
echo "Login Failed";
}
} else {
print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
} else {
print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: '.$page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
和着陸頁
<?php
session_start();
//user logged in??
if ($_session['logged in'] != 'Y') {
//No- jump to log in page.
header("location: 3.php");
exit();
}
else
{
echo 'this works';
}
?>
'if($ _session ['logged in']!='Y')'這是你的問題。認爲「信箱」。想*超全球* http://php.net/manual/en/language.variables.superglobals.php *和比較* ;-) –
我瞎了嗎?你在哪裏設置$ _SESSION ['登錄']?如果你不通過mysql傳遞,你爲什麼要逃避用戶輸入密碼?你應該至少哈希你的密碼在分貝,爲了隱私的原因:) – Florian
請[停止使用'mysql_ *'函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use- MySQL的函數式的PHP)。他們不再被維護,並[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。瞭解[準備的陳述](http://en.wikipedia.org/wiki/Prepared_statement),並考慮使用[PDO](http://jayblanchard.net/demystifying_php_pdo.html)。 –