Redirect to login page if user is not logged in

php, redirect

Solution

Set a session after login successful and in edit.php check for it, if session is not set, redirect it to homepage.

login.php :

//put this at the first line
session_start();
//if  authentication successful 
$_SESSION['login'] = true;

edit.php :

if(!$_SESSION['login']){
   header("location:index.php");
   die;
}

Problem

I created my website, but I want to require users to log in before they can access certain pages. For example, my home page is index.php, having url (www.sample.com/index.php). There is a login button in this page will redirect to login.php. In login.php page I have an edit button, and `onclick` event takes to edit.php. Now, if I paste the URL www.sample.com/edit.php in the addressbar, it goes directly to edit.php, but I want it to take to index.php if the user is not logged in, similar to how Google requires authentication.

Original source