Hi what's the code to keep the login safe. I mean after people login by entering username and password, I do not want other user to be able to access my web admin just by entering the url without login first.

Notes the admin folder has many pages too which is restricted only for administrator.

How to keep those pages secure ?

I already write the login page, but as of now, others can enter admin page by just entering the url.

My friend, is not complex to do it, but must tell you, I dont do something like this in years, since i started using some RAD tools, they will create that automatically for, o will not lose time developing those security stuff anymore?

Is it good? the code? yes, good for me? yes, saves me time, but it starting to create a gap on some specific knowledge about programation.

Hi davy_yg,

first, put a file named ".htaccess" in the folder you want to protect. Right now, I'm not sure, if you actually have to put something in it, or if apache won't let anyone access that page when the file exists. Just fish for some info if it's not working.

Then you have to give permission to each user that shall be allowed to access these page. Simply put a flag in your database and check on top of a script (put somewhere else than your protected folder) whether it is set or not. If the access is granted, you can include these file width "include" oder "require".
Apache will only deny HTTP-accesses. With PHP, you can still work with that folder like before.

I'm wondering if that all. But I can't think of anything else to do... Try it out and report if it's not working.

Hope that helps, Simon

I receive this error:

Deprecated: Function session_is_registered() is deprecated in C:\xampp\htdocs\Masterlink\cgoods\admin.php on line 28

admin.php

<?php 

session_start(); 

if(!session_is_registered("username")){  

//re-direct ke index.php  
header("location:index.php");  
}  

?>

I place the above code on top of admin page.

The function session_is_registered() is deprecated (as the notice says) which means that it might be dropped in future and you are discouraged to use it. See http://php.net/manual/en/function.session-is-registered.php. Check the session variable instead, which has the same effect:

<?php 

session_start(); 

if(!isset($_SESSION['username']){
 
    //re-direct ke index.php
    header("location:index.php");
}

?>

.

there are couple of security issues to deal with
1. Prevent unauthorized logins. Here you will meet th greatest threat, SQL injection. Once you deal with that thru data validation, whitelisting and preparedstatements you are ready for next challenge.

2. You need to prevent your authentication data mostly session from being hijacked and used against system. Here you will meet jargons like session fixation et al. This can be fixed using differen techniques already on the net if you be dilligent in searching.

3. Lastly you will need to check what you are inputting/outputting. User data are never to trust, so validation validation validation then cleaning. Also when you output data you need to escape them to prevent any XSS attacks

So in summary:
Guard against SQL injection
Protect your session from any attacks
Validate/Escape inputs and outputs from and to users/browsers

I would suggest you do it if you think your level allows you or that your site is not storing sensitive info. Else I would suggest you check ready made solutions or use something like OpenID

The simple answer to your question. On every page you want to protect, you need to check if the user is logged in.

How to check if the user is logged in depends on your implementation.

Heres is a simple login scenario:


1) Login page with {user} and {pass}
2) Validate {user} and {pass} and issue that user a {session_key}
3) On every page you protect, check for valid {session_key}

That is all there is to password protected pages.

The function session_is_registered() is deprecated (as the notice says) which means that it might be dropped in future and you are discouraged to use it. See http://php.net/manual/en/function.session-is-registered.php. Check the session variable instead, which has the same effect:

<?php 

session_start(); 

if(!isset($_SESSION['username']){
 
    //re-direct ke index.php
    header("location:index.php");
}

?>

.

I did try placing:

<?php 

session_start(); 

if(!isset($_SESSION['username'])){
//re-direct ke index.php  

header("location:index.php");  
}  

?>

above the admin.php (admin page) but why I am still able to enter the admin page simply by typing ../admin.php without login ?

One possible reason could be that you are only checking for the existence of username in the session but not the value of it. Try it this way:

<?php 
session_start(); 

// say that user johnybegoode has successfuly logged in and $_SESSION['username'] was set
// to johnybegoode

if(!isset($_SESSION['username'] or $_SESSION['username'] !='johnybegoode')){
// re-direct ke index.php  

header("location:index.php");  
}  
?>

Another reason could be that you do not unset $_SESSION upon unsuccessful login or upon logout.

One possible reason could be that you are only checking for the existence of username in the session but not the value of it. Try it this way:

<?php 
session_start(); 

// say that user johnybegoode has successfuly logged in and $_SESSION['username'] was set
// to johnybegoode

if(!isset($_SESSION['username'] or $_SESSION['username'] !='johnybegoode')){
// re-direct ke index.php  

header("location:index.php");  
}  
?>

Another reason could be that you do not unset $_SESSION upon unsuccessful login or upon logout.

admin.php

<?php 

session_start(); 

if(!isset($_SESSION['username'] and $_SESSION['username'] !='guest')){
//re-direct ke index.php  

header("location:index.php");  
unset($_SESSION['username']);
}  

?>

Parse error: syntax error, unexpected T_LOGICAL_AND, expecting ',' or ')' in C:\xampp\htdocs\Masterlink\cgoods\admin.php on line 28

line 28: if(!isset($_SESSION and $_SESSION !='guest')){

Sorry, my typing error. It should be:

if(!isset($_SESSION['username']) and $_SESSION['username'] !='guest'){

I usualy check code before I post but haven't done so this time.

admin.php

session_start(); 

if(!isset($_SESSION['username']) and $_SESSION['username'] !='user'){
//re-direct ke index.php  

header("location:index.php");  
unset($_SESSION['username']);
}  

?>

<div id="header">
      <p><a href="#">Home </a>| <a href="index.php">Logout </a>| <a href="admin.php">Admin Panel</a></p>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
    </div>

oh, I wonder why I still able to enter the admin panel just by typing ../admin.php on the url. Maybe I have not unset session yet. How to code the unset upon logout ?

on click logout - unset($_SESSION); ?

Also, is there any other necessary code before this that I need to type to set session ?

On your loging page you should start with

// start session
session_start();

// unset any session data until user submits valid username and password
unset($_SESSION);

Then when user enters a valid username (i.e johnybegoode) and password set session variables you need, such as

$_SESSION['username'] = 'johnybegoode';

Then on other pages for that user first check for valid username using the code from previous post

<?php 
session_start(); 

// say that user johnybegoode has successfuly logged in and $_SESSION['username'] was set
// to johnybegoode

if(!isset($_SESSION['username'] or $_SESSION['username'] !='johnybegoode')){
// re-direct ke index.php  

header("location:index.php");  
}  
?>

Then provide a logout link which points to the login page. When user clicks on it (logs out) the session is unset on the login page first.

Option 2: Your logout link can point to some other page (logout.php) where you can thank the user, unset session, do other cleanup, log the event etc and automaticaly redirect to login page.

Note: you can not unset session with javascript onclick directly, you have to use ajax and implement a javascript function that calls a php script that unsets the session but that is a more complex topic.

Even more important note: in this example there was nothing said about security. Make sure you do all the security exercises when dealing with input and session. See previous posts in this thread and other threads here and arround.

Well, this is some things that I have done:

This is the code to proses the login page:

proseslogin.php

<?php

// start session
session_start(); 

// unset any session data until user submits valid username and password
unset($_SESSION);

$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$login = isset($_POST['login']) ? $_POST['login'] : '';

//function
function periksa ($username, $password){
		if (($username=="guest") and ($password=="guest")){
			return true;
		}else{
			return false;
		}
	}	
	
// cek		
if (periksa($username, $password)) {
		$login=true;	
}
else {
		echo "Wrong user ID or password!";
		
		header("Location: http://localhost/Masterlink/cgoods/index.php");
}
if ($login) {
	echo "<br>Di sini blok aplikasi setelah login dilakukan";
	echo "<br>You are successfully login!";
	
	// buat session username
	$_SESSION['username'] = 'guest';	
	header("Location: http://localhost/Masterlink/cgoods/admin.php");
	Exit();
}


?>

This is the code on top of the admin page:

admin.php

<?php 

session_start(); 

if(!isset($_SESSION['username']) and $_SESSION['username'] !='guest'){
//re-direct ke index.php  

header("location:index.php");  
unset($_SESSION['username']);
}  

?>

<div id="header">
      <p><a href="#">Home </a>| <a href="logout.php">Logout </a>| <a href="admin.php">Admin Panel</a></p>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
    </div>

logout.php

<?php

echo "You will be logout from the admin page.";

// unset any session data 
unset($_SESSION);
		
header("Location: http://localhost/Masterlink/cgoods/index.php");
Exit();


?>

My question is why I am still able to enter the admin page (../admin.php) without login or just by typing the url ?

what's lacking in my codes ?

On the proseslogin.php page, line 39 shoud make more sense if it was:

$_SESSION['username'] = $username;

so it works for any user.

On the admin.php page do unset first and then redirect (swap lines 9 and 10).

On the admin.php page the condition statement is wrong. It should be:

if(!isset($_SESSION['username']) or $_SESSION['username'] !='guest')

But I am confused here since I assume that guest should not be allowed to access admin page!? So what is really the condition you want to check?

guest is just sample user. I won't use that user in actual.

but the thing is I am still able to access the admin page just by typing ../admin.php

I already fix the code as directed. I also already logout.

I try to login back just by typing the previous url ../admin.php and I directly login to admin without having to type the username and password.

Make sure you do not send any character (not even a space) before header directive on line 9 otherwise the header will not be sent. You can test that if you put the code

if(headers_sent()) {
    echo 'Headers have already been sent';
}

after line 10 on admin.php. If you see this notice than you have sent some contents before sending the headers.

If you post complete code for your pages I can test them in my environment but not before tomorrow since I have to finish a project for the customer tonight. Meanwhile you can put the following code:

print_r($_SESSION);

or

die($_SESSION);

in various places to check wheter the contents of the session is what it should be. Appropriate places would be lines 8 and 12 in admin.php, line 8 in logout.php etc.

unset session then destroy it

unset($_SESSION);
session_destroy();

Now, after I destroy session, I cannot login at all to admin.php by entering the url nor by login.

I insert session_destroy(); by accident in proseslogin.php instead of in logout.php only. Now I leaving session_destroy(); in logout.php only.

I still unable to login though evenif I enter the correct username and password.

----------

Nevermind, I am able to login back by using the correct username and password after commenting out unset($_SESSION); in proseslogin.php and using it back. But then, the condition returning to first condition where I am able to enter admin.php by url besides login.

Now, after I destroy session, I cannot login at all to admin.php by entering the url nor by login.

I insert session_destroy(); by accident in proseslogin.php instead of in logout.php only. Now I leaving session_destroy(); in logout.php only.

I still unable to login though evenif I enter the correct username and password.

----------

Nevermind, I am able to login back by using the correct username and password after commenting out unset($_SESSION); in proseslogin.php and using it back. But then, the condition returning to first condition where I am able to enter admin.php by url besides login.

We cannot say for sure, we cannot see what is in your family!

Make sure you do not send any character (not even a space) before header directive on line 9 otherwise the header will not be sent. You can test that if you put the code

if(headers_sent()) {
    echo 'Headers have already been sent';
}

after line 10 on admin.php. If you see this notice than you have sent some contents before sending the headers.

If you post complete code for your pages I can test them in my environment but not before tomorrow since I have to finish a project for the customer tonight. Meanwhile you can put the following code:

print_r($_SESSION);

or

die($_SESSION);

in various places to check wheter the contents of the session is what it should be. Appropriate places would be lines 8 and 12 in admin.php, line 8 in logout.php etc.

I just did adding print_r($_SESSION); next to session. I cannot see it printed though. The proseslogin.php and logout.php is already the whole code. The admin.php evenif not the whole code, I think it's enough for you to test it, the rest is just the content.

session_start() on top of a page?

I have made some changes to your code and it works perfectly well in my browser. Changes are in comments.

Main thing is that you should use session_unset() php function to unset the session (I wrongly advised you to use unset($_SESSION) which is not recommended, sorry). See http://php.net/manual/en/function.session-unset.php and also read the comments. The rest is in code which is largely simplified, so it needs to be worked upon before the production! Hope it helps.

index.php (login page)

<?php

    // start session
    session_start();

    // unset any session data until user submits valid username and password
    // this is correct way not unset($_SESSION), sorry my mistake
    // see http://www.php.net/manual/en/function.session-unset.php
    session_unset();
    session_destroy();

?>

<h3>Login</h3>
<form method="post" action="proseslogin.php">

    <div>
    <labelfor="username">Username</label>
    <br />
    <input type="text" name="username" />
    </div>

    <div>
    <labelfor="password">Password</label>
    <br />
    <input type="password" name="password" />
    </div>

    <div><input type="submit" name="submit" value="submit" /></div>

</form>

proseslogin.php

<?php

// start session
session_start();

    $username = $_REQUEST['username'];
    $password = $_REQUEST['password'];

    // *** set login to false not to '' to be consistent with the return value
    // *** of the function periksa()
    $login = isset($_POST['login']) ? $_POST['login'] : false;

    // DEBUG CODE 1
    // uncomment last two lines and you should see the values that were
    // sent by the login form
    //
    // print_r($_REQUEST);
    // die();

//function
function periksa ($username, $password){

    if (($username=="guest") and ($password=="guest")){

        return true;

        } else {

            return false;
        }
    }

// cek
if (periksa($username, $password)) {

    $login=true;

} else {

    echo "Wrong user ID or password!";

    header("Location: index.php");
}

if ($login) {

    // *** This code will not get displayed since you are immediately being
    // *** redirected to the admin.php page so move it to the admin page
    echo "<br>Di sini blok aplikasi setelah login dilakukan";
    echo "<br>You are successfully login!";

    // buat session username
    $_SESSION['username'] = $username;
    header("Location: admin.php");

    // *** exit function should be in lowercase and is actually
    // *** not realy neccessary here
    exit();
}
?>

admin.php

<?php

    session_start();

    if(!isset($_SESSION['username']) or $_SESSION['username'] !='guest'){

        // unset and destroy the session
        session_unset();
        session_destroy();

        //re-direct ke index.php
        header("location:index.php");
    }
?>

<div id="header">
      <p><a href="#">Home </a>| <a href="logout.php">Logout </a>| <a href="admin.php">Admin Panel</a></p>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
</div>

logout.php

<?php

    session_start();

    // *** This code will not get displayed since you are immediately being
    // *** redirected to the index page
    echo "You will be logout from the admin page.";

    // unset any session data
    session_unset();
    session_destroy();

    header("Location: index.php");

    // *** exit function should be in lowercase and is actually
    // *** not realy neccessary here
    exit();
?>

i do agree with broj1,
he is correct..

from the login page itself,.
the session starts,..

/"login page code"/

just assume that the $_POST["username"] contains username entered through a post form, and you are sending it to firstpage.php..

<?php

if ( isset($_POST["username"]) && !empty($_POST["username"]) )

{
session_start();

$u = $_POST["username"];

$_SESSION= $u;

header("location:firstpage.php");

}
?>
//

now at the firstpage.php,..

check if the user is logged in with session or not.,,. if not, send header to index.php.

/*******firstpage code, on top*********/
<?php
session_start();

$_SESSION = $u;

if ( !isset($_SESSION) )
{
header("location:index.php");
}

?>

try this on,,
i guess this will solve the problem..

How can anyone in the world write form like this

<form method="post" action="proseslogin.php">

and catch by this?

$username = $_REQUEST['username'];

Use explicitly $_POST or $_GET

Hi, I am facing similar problem. What script should I place on top of every admin-related page, so that no user will be able to access them simply by entering the url?

I try to place the following code on top of banner_manager.php

<?php     
session_start();     

if(!isset($_SESSION['username']) or $_SESSION['username'] !='guest'){

// unset and destroy the session        

session_unset();        
session_destroy();         //re-direct ke index.php        

header("location:index.php");    }?>

Other user yet still able to access it simply by entering the url.

you want that, no users should visit the page, if they haven't got the session...
so just check for the session, if it is not..
simply redirects it to index.php..

<?php
session_start();

if ( !isset($_SESSION) )
{
header("location:index.php");
}


?>

if, there is no session, no needs to unset or destroy it..
just check it, for the session name..
and that's all..

this code should be placed on every page, after the user has entered the username and password..where you want to hide the page..

and you are starting the session and giving the value of session variable, to that user..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.