创建PHP登录会话 [英] Create session for php login

查看:75
本文介绍了创建PHP登录会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个小型网站创建一个管理员登录,我正在为该管理员访问网站后台提供服务,但我对会话(以及一般而言的php)了解得很少.

I'm creating an admin log-in for a small website that i'm making for the admin gets acess to the website back office but i understand very little about sessions (and php in general).

有两个页面:admin.php(管理员登录所在的页面)和backoffice.php(登录成功后将管理员重定向到此处).

There are two pages: admin.php (is where the admin logs in) and backoffice.php (the admin is redirected to here after the log-in is sucessfull).

为管理员创建会话的最简单方法是什么,以使用户无法仅通过转到"www.example.com/backoffice.php"来访问后台?

What's the simplest way to create a session for the admin so a user can't access the backoffice just by going to "www.example.com/backoffice.php" ?

我不知道这是否有兴趣,但这是我用来登录管理员的PHP:

I don't know if this has any interest, but here's the PHP i use to log-in the admin:

<?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();
?>

推荐答案

在代码顶部添加

session_start();

替换

if ($count==1) {
header( "refresh:0;url=backoffice.php" );

}

使用

if ($count==1) {
    header( "refresh:0;url=backoffice.php" );
$_SESSION['logged']="true";
} 

然后,在backoffice.php中,将其放在顶部

Then, in backoffice.php, put at the top

<?php
session_start();
if($_SESSION['logged']!="true"){echo 'Error! You\'re not logged in!';}
else{//your code
}
?>

这篇关于创建PHP登录会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆