如何只为登录用户保护页面? [英] How do I protect a page only for logged users?

查看:109
本文介绍了如何只为登录用户保护页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个很好的登录表单.但是我意识到我的用户所指向的页面仍然可以被任何人访问.如何保护只有已登录用户才能访问的页面?

I created a login form that works great. But I realized the page my user is directed to can still be accessed by anybody. How do I protect the page being accessed only viewable by those logged in?

我需要在成功页面本身上放置一个脚本吗?

Do I need to place a script on the success page itself?

这是我的check_login.php:

Here is my check_login.php:

<?php
$host="localhost"; // Host name
$username="xxx"; // Mysql username
$password="xxx"; // Mysql password
$db_name="xxx"; // Database name
$tbl_name="xxx"; // Table name

// Connect to server and select database.
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);

$count=mysql_num_rows($result);

$user_info = mysql_fetch_assoc($result);

 if( isset($user_info['url']) ) {

 session_register("myusername");
 session_register("mypassword");
     header('Location: ' . $user_info['url']); //Redirects to the supplied url from the DB
 } else {
  header("location:error.htm");
 }
 ?>

推荐答案

您的每个页面都应以

session_start();

,从PHP 4.2版开始,您不应该使用session_register( "variablename" ),请使用

and you should not be using session_register( "variablename" ) as of PHP version 4.2, use

$_SESSION["variable"] = value;

具有is-logged-it检查功能的示例页面为:

so example page with is-logged-it checking would be:

<?php
session_start();
if($_SESSION["loggedIn"] != true) {
    echo("Access denied!");
    exit();
}
echo("Enter my lord!");
?>

和登录脚本:

<?php
    /*
        ... db stuff ...
    */

if( isset($user_info['url']) ) {
    $_SESSION["loggedIn"] = true;
    $_SESSION["username"] = $myusername;
    header('Location: ' . $user_info['url']); //Redirects to the supplied url from the DB
} else {
    header("Location: error.htm");
}
?>

这篇关于如何只为登录用户保护页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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