PHP if / else运行不正常

时间:2016-02-08 20:48:59

标签: php session getcwd

enter image description here我试图在PHP中使用if / else语句。目前我要做的是,$_SESSION['usr'];是否等于用户尝试访问的当前目录($dir_auth2)变量。然后他们可以访问我在其中的目录或index.php。否则,如果$_SESSION['usr'];!=到当前目录,则将它们重定向到主页。目前,当用户键入别人的目录时,他们可以访问它。

<?php
session_name('tzLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();
//This if statement below is the problem
if($_SESSION['usr'] == $dir_auth1) {
  //This demo.php is the home page
  header("Location: demo.php");

} else {
  echo "You are logged in as " . $dir_auth1;
} 



$dir = getcwd();
$dir1 = str_replace('/home/pophub/public_html/', '/', $dir);


$dir_auth = getcwd();
$dir_auth1 = str_replace('/home/pophub/public_html/gallry/', '', $dir_auth);
echo $_SESSION['usr'];
echo $dir_auth1;

 $dir_user = getcwd();
 $dir_user1 = str_replace('/home/pophub/public_html/gallry', '', $dir_user);


?>

2 个答案:

答案 0 :(得分:1)

您没有发布整个脚本,也没有在任何地方定义$dir_auth2。这很糟糕,因为你在

中依赖它的价值
if($_SESSION['usr'] == $dir_auth2) {

此外,您应在致电die()

后使用header()
header("Location: demo.php");
die();

How to make a redirect in PHP?

答案 1 :(得分:1)

我认为这是你正在寻找的。

在尝试在if / else语句中使用变量之前,您需要定义变量$dir_auth1

另外,我认为你想要的是!=而不是==

<?php
session_name('tzLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();

$dir = getcwd();
$dir1 = str_replace('/home/pophub/public_html/', '/', $dir);
$dir_auth = getcwd();
$dir_auth1 = str_replace('/home/pophub/public_html/gallry/', '', $dir_auth);
$dir_user = getcwd();
$dir_user1 = str_replace('/home/pophub/public_html/gallry', '', $dir_user);


if($_SESSION['usr'] != $dir_auth1) {
    header("Location: demo.php");
} else {
    echo "You are logged in as " . $dir_auth1;
} 
?>

此外,您可以将所有字符串函数组合成一个如下:

$dir_auth1 = str_replace(array("/home/pophub/public_html/","/home/pophub/public_html/gallry/"),"",getcwd());