PHP (Core & Framework)

How to restrict access to your PHP pages by logged in users only

php-session-check-login

You want that only Logged in users can access your php pages, in case user is not Logged in , he should be redirected to login page. This feature can be achieved very easily by few lines of php code.

First you need to make sure that when some user Logged in to your site , you save some value say userID in php session like below :

 <?php
// use the following code in your login page 
$_SESSION['userID']=$row['user_id'];

// do no forget to use  <?php  session_start();?> in first line of your php page

?>

Now you need to create one separate file say userAuth.php, We will use this file to check if user is Logged in or not , if user is not Logged in it will redirect the user to login page. You need to include this file in your php pages . See the code below for userAuth.php

<?php 
session_start();
if($_SESSION['userID']=="")
	header("Location: login.php"); 

?>