我正在爲一個小型網站創建管理員登錄,我爲管理員獲取訪問網站後臺,但我對會話(以及一般的php)瞭解甚少。爲php登錄創建會話
有兩個頁面:admin.php(是管理員登錄的地方)和backoffice.php(管理員在登錄成功後重定向到此處)。
爲admin創建會話最簡單的方法是什麼,所以用戶無法訪問後臺只需轉到「www.example.com/backoffice.php」?
我不知道這有什麼興趣,但這裏的PHP我用它來登錄管理員:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="dragoesmurtosa"; // Database name
$tbl_name="login"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password") or die(mysql_error());
mysql_select_db("$db_name") or die(mysql_error());
// Check $username and $password
if(empty($_POST['username']))
{
echo "UserName/Password is empty!";
return false;
}
if(empty($_POST['password']))
{
echo "Password is empty!";
return false;
}
// Define $username and $password
$username=$_POST['username'];
$password=($_POST['password']);
// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if ($count==1) {
header("refresh:0;url=backoffice.php");
} else {
echo "Wrong password, you'll be sent to the login page";
header("refresh:3;url=admin.php");
}
ob_end_flush();
?>
你用會話的任何地方我還沒有看到。所以使用會話。 http://php.net/session_start – Halcyon
'session_start();''$ username = $ _POST ['username'];''$ _SESSION ['username'] = $ username;''if(isset($ _ SESSION [ '用戶名'])){//給予訪問}'基本上。或者'if(!isset($ _ SESSION ['username'])){//引導它們'' –
在每個腳本中放置一個網關。 '在session_start(); if(!$ _ SESSION ['is_admin']){redirect_elsewhere(); }'。 –