Lilly Shk
Lilly Shk

Reputation: 147

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);

Upvotes: 0

Views: 81

Answers (1)

Anoop S
Anoop S

Reputation: 141

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()

Upvotes: 1

Related Questions