简体   繁体   中英

Restricting direct access to php file

I have an index.php file where I login and move to another file called map.php from where on clicking button I reach inc.php .

The problem is on typing the link localhost/lilly/inc.php the unauthorised user or any public user should not be able to access this file, only the person logged in should!

How can I do this? I have read about using .htaccess etc but I have completely not understood anything from other articles..

I have used inc.php:

if(!defined('MyConst')) {
   die('Direct access not permitted');
}

Map.php:

define('MyConst', TRUE);

Use sessions for your requirement.

In your index.php page, start a session and store the user id (or any other data to uniquely identify the user) after someone is logged in.

index.php:

session_start();
$_SESSION['user_id'] = $user_id; // $user_id is the user id of the logged in user

And check the existence of the user_id in the inc.php file

inc.php:

if (!isset($_SESSION['user_id'])
header("Location:index.php"); // redirect to index.php page if the user is not logged in

References:

$_SESSION , session_start()

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