简体   繁体   中英

PHP redirect users if not logged in

I am searching for a way to redirect all users that are not logged in from any file in a specific directory.

I have a directory called admin .

The only user with a login will be myself.

I use a script such as this to check if I am logged in and if not then redirect.

if(isset($_SESSION['user']) {
 if($_SESSION['user'] == "username") {
   echo "Welcome, " . $_SESSION['user'];
}
else {
 header("Location: index.php");
}
}

Pretty simple. Pretty straight forward. No need for extra security since I am not handling any sensitive data and my admin pages cannot interfere with how my site runs.

But how could I create a redirect to check for that specific admin directory?

This script is in my functions.php file which is included on every single page so I need a way to exclude every file except that directory or if it's possible to use an array and just list the pages that should not be viewable unless logged in.

With some tweaking I was thinking something like this would work.

Problem is what if I have two index.php files? One for main directory and one for my subdirectories?

I included $directory = "admin/"; in the script, but I'm not sure how to work that into it to only redirect if those files are in that directory.

Notice: I wrote these examples in a hurry so they may have other errors. Sorry if they do.

if(isset($_SESSION['user']) {
 if($_SESSION['user'] == "username") {
   echo "Welcome, " . $_SESSION['user'];
}
else {
 $directory = "admin/";
 $redirect[] = array();
 $redirect[] = "page1.php";
 $redirect[] = "page2.php";
 if (in_array(($_SERVER["SCRIPT_FILENAME"], $redirect)) {
  header("Location: index.php");
}
}
}

How can I add the directory to the code?

If i understand your question correctly, you want anybody without a $_SESSION['user'] accessing a file within the /admin/ directory to be redirected?

if (!isset($_SESSION['user']) && stristr($_SERVER['SCRIPT_FILENAME'],'admin'){
   header('Location: http://www.goodbye.com');
}

Notice the full URL, including http in the header. an HTTP header must have a full, absolute URL to function properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM