frothaemumep frothaemumep - 5 months ago 8
PHP Question

How to reject accessing a user to a custom file in php

I've got a question.. I have 3 main files on my root directory which looks like this:

1- index.php
2- login.php
3- dashboard.php


Basically If a user goes to my site ,he will redirected automatically to
index.php
file which contains a captcha code & if he enters the correct code ,he will redirected to the
login.php
file. So he can use his information to sign in to the
dashboard.php
file.

The problem is ,he can access to the login page without entering any code at index page. for example he can go to this url and access the login page manually:

http://www.example.com/login.php

Is there a way to reject and deny the accessing of a user from a custom page ? So in this situation ,he MUST access the index page and after that he will be redirected to the login page.

It would be very helpful if you know how to solve this question ... Thanks in advance!

Answer

I have this at the top of each of my pages. If the session variable is not set, provide a link to the login page (this could be a redirect if you want), and do not display anything else. If the session variable has been set, meaning the user is logged in, then proceed with displaying the page.

<?php

//start the session
session_start(); 

//If the user is not logged in, 
if (!isset($_SESSION["CurrentUser"])){ ?>
            <a href="login.php"' >Click here to Login</a>

    <?php
    exit(); //Do not display the rest of the page

//If the user is logged in, 
}else{
    require_once('top.php');
  //in addition to including top.p php, the code below this line will execute.
}


?>

On your login page, wherever you do the authentication piece, just add this upon successful login.

 $_SESSION["CurrentUser"] = $username
Comments