仅在使用php登录时访问页面 [英] access page only if logged in with php
问题描述
我是PHP的新手,我希望只有在用户登录后才能访问页面. login2.php:
I'm new to PHP, and I want to make possible to access a page only if a person is logged in. login2.php:
<?php
$host="hostxyz";
$dbusername="userxyz";
$dbpassword="xyz";
$db_name="dbxyz";
$tbl_name="tblxyz";
mysql_connect("$host", "$dbusername", "$dbpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$username=$_POST['username'];
$password=$_POST['pwd'];
$encryptedpwd=sha1($password);
$username = stripslashes($username);
$encryptedpwd = stripslashes($encryptedpwd);
$username = mysql_real_escape_string($username);
$encryptedpwd = mysql_real_escape_string($encryptedpwd);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and pwd='$encryptedpwd'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
$_SESSION['username'] = $username;
$_SESSION['pwd'] = $encryptedpwd;
header("location:login_success.php");
}
else {
echo "Username e/o password errata.";
}
?>
login_success.php:
login_success.php:
<?php
session_start();
if($_SESSION['username']){
header("location:area_utenti.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
area_utenti.php(翻译成member_area.php):
area_utenti.php (member_area.php translated):
<?php
session_start();
if(!isset($_SESSION['username'])) {
header("location:dologin.html");
}
?>
<html>
<head>
<title>Area Utenti</title>
</head>
<body>
<p>Sei loggato, bravoh!</p>
</body>
</html>
dologin.html只是一个页面,如果未注册/未登录的用户尝试访问成员区域,则该页面将被重定向. 问题是登录后,我应该重定向到area_utenti.php,但是area_utenti.php会将我重定向到dologin.html.我做错什么了? 对不起,英语不好.
dologin.html is simply a page where unregistered/unlogged users are redirected if they try to access to member area. The problem is that after I log in, I should be redirected to area_utenti.php, but area_utenti.php redirects me to dologin.html. What did I do wrong? Sorry for bad English.
P.S .:我试图在StackOverflow上搜索解决方案,并尝试应用它们,但是它们不起作用.
P.S.: I tried to search for solutions on StackOverflow, and I tried to apply them, but they didn't work.
推荐答案
您忘了在其中一个脚本中启动会话,也许就是这个问题,也许值得检查一下:
You forgot to start the session in one of your scripts, maybe thats the issue, might worth checking it:
<?php
session_start();
$host="hostxyz";
$dbusername="userxyz";
$dbpassword="xyz";
$db_name="dbxyz";
$tbl_name="tblxyz";
//...rest of your code...
这篇关于仅在使用php登录时访问页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!