Securing a Webpage: User Must Login

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sby247
Forum Newbie
Posts: 8
Joined: Thu Oct 20, 2011 5:50 am

Securing a Webpage: User Must Login

Post by sby247 »

I have a problem with my webpage secure script. Even after logout, wen I hit the back button on my browser, I can still access the secure page. I can still even access the assigned page without login instead of redirecting to "login.php". I don't know what might be wrong with the variable or scripting. I have tried the "||", "&&" and "or" variable and it work. Here is the secure page script.

Code: Select all

<?php
	//Start session
	session_start();
	
	//Check whether the session variable SESS_MEMBER_ID is present or not
	if(!isset($_SESSION['login']) xor (trim($_SESSION['login']) == '')) {
		header("location: login.php");
		exit();
	}
?>

Here is the logout out script :

Code: Select all

<?php
//Start session
session_start();
session_destroy();

//Unset the variables stored in session
unset($_SESSION['login']);
 
//Redirect use to login page
header("location: login.php");

Please I need to get this resolve ASAP. Thanks in anticipation.
Last edited by Benjamin on Thu Oct 20, 2011 1:55 pm, edited 2 times in total.
Reason: Added [syntax=php|sql|css|javascript] and/or [text] tags.
sby247
Forum Newbie
Posts: 8
Joined: Thu Oct 20, 2011 5:50 am

Re: Securing a Webpage: User Must Login

Post by sby247 »

Do u mean if i write it like this...

Code: Select all

<?php
	//Start session
	session_start();
	
	//Check whether the session variable SESS_MEMBER_ID is present or not
	if(!isset($_SESSION['login']) or (||) (trim($_SESSION['login']) == '')) {
		header("location: login.php");
		exit();
	}
?>
Would it work like this??

Also...if I write it as adviced...

Code: Select all

?php
	//Start session
	session_start();
	
	//Check whether the session variable SESS_MEMBER_ID is present or not
if !isset($_SESSION['login']) = not set = 1 And  if (trim($_SESSION['login']) == '') not set = 1{
header("location: login.php");
		exit();
Please advice or help me write it the way it should be,

NB. Am a newbbies.
Last edited by Benjamin on Thu Oct 20, 2011 1:56 pm, edited 1 time in total.
Reason: Added [syntax=php|sql|css|javascript] and/or [text] tags.
Dodon
Forum Commoner
Posts: 64
Joined: Wed Aug 03, 2011 4:11 am
Location: Netherlands

Re: Securing a Webpage: User Must Login

Post by Dodon »

No, like this.

Code: Select all

if(!isset($_SESSION['login']) || (trim($_SESSION['login']) == '')) {
 header("location: login.php");
 exit();
 }
 
sby247
Forum Newbie
Posts: 8
Joined: Thu Oct 20, 2011 5:50 am

Re: Securing a Webpage: User Must Login

Post by sby247 »

@ Dodon.....

I have tried using this but it would just refresh back to "login.php". Initially, I was using this method with godaddy and it works fine not until I changed hosting and it won't work not until I used the "xor" method. Why this script don't work with some other hosting (fatcow in particular).

Code: Select all

if(!isset($_SESSION['login']) || (trim($_SESSION['login']) == '')) {
 header("location: login.php");
 exit();
 }
I don't knw which better method to use. I am kinda feed up...but need a solution to this.
Last edited by Benjamin on Thu Oct 20, 2011 1:56 pm, edited 1 time in total.
Reason: Added [syntax=php|sql|css|javascript] and/or [text] tags.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Securing a Webpage: User Must Login

Post by flying_circus »

sby247 wrote:@ Dodon.....

I have tried using this but it would just refresh back to "login.php". Initially, I was using this method with godaddy and it works fine not until I changed hosting and it won't work not until I used the "xor" method. Why this script don't work with some other hosting (fatcow in particular).

if(!isset($_SESSION['login']) || (trim($_SESSION['login']) == '')) {
header("location: login.php");
exit();
}

I don't knw which better method to use. I am kinda feed up...but need a solution to this.
Why are you trimming the result of a comparison operation?

empty() will check to see if $_SESSION['login'] is considered empty.

Code: Select all

<?php
  //Start session
  session_start();
 
  //Check whether the session variable SESS_MEMBER_ID is present or not
  if(!isset($_SESSION['login']) || empty($_SESSION['login'])) {
    header("location: login.php");
    exit();
  }
?>
sby247
Forum Newbie
Posts: 8
Joined: Thu Oct 20, 2011 5:50 am

Re: Securing a Webpage: User Must Login

Post by sby247 »

@fly_circus...

I tried using your formular...but it is redirecting me to "login.php". I am just so confused why all method is not working out. I just want a formular where the webpage can be secure upon sign in and sign out. The formular don't seems to work bt redirecting to "login.php". Is there something wrong??
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Securing a Webpage: User Must Login

Post by flying_circus »

sby247 wrote:I tried using your formular...but it is redirecting me to "login.php". I am just so confused why all method is not working out.
Either $_SESSION['login'] is not set or it is empty.

What is stored in the session vars?

Code: Select all

<?php
   //Start session
   session_start();
  
   print_r($_SESSION);
 ?>
sby247
Forum Newbie
Posts: 8
Joined: Thu Oct 20, 2011 5:50 am

Re: Securing a Webpage: User Must Login

Post by sby247 »

flying_circus...

Session vars...u mean the vars in "checklogin.php" upon login??. Sorry as am newbie...
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Securing a Webpage: User Must Login

Post by Benjamin »

Forum Rules wrote: 11. Please use proper, complete spelling when posting in the forums. AOL Speak, leet speak and other abbreviated wording can confuse those that are trying to help you (or those that you are trying to help). Please keep in mind that there are many people from many countries that use our forums to read, post and learn. They do not always speak English as well as some of us, nor do they know these aberrant abbreviations. Therefore, use as few abbreviations as possible, especially when using such simple words.
You may also want to read:
  1. General Posting Guidelines
  2. Posting Code in the Forums
  3. PHP Manual
  4. PHP Tutorials
Please use the appropriate

Code: Select all

 [ /code] tags when posting code blocks in the forums. Functions in your code will be automatically linked to manual entries and your code will be syntax highlighted making it much easier for everyone to read. You will most likely receive more answers as well.
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: Securing a Webpage: User Must Login

Post by novice4eva »

to your logout script try adding

Code: Select all

$_SESSION = array();

before you send the header. Throw that into the mixture and lets see what happens.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Securing a Webpage: User Must Login

Post by flying_circus »

sby247 wrote:flying_circus...

Session vars...u mean the vars in "checklogin.php" upon login??. Sorry as am newbie...
No, I mean the session vars.

A Session is a way to make data persist across a user's visit to your website. You can learn about sessions here:

http://www.php.net/manual/en/intro.session.php
sby247
Forum Newbie
Posts: 8
Joined: Thu Oct 20, 2011 5:50 am

Re: Securing a Webpage: User Must Login

Post by sby247 »

@flying_circus...

Is there anyway you can help me in resolving this. I am just so confuse and need to get this fixed asap. Please help.
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: Securing a Webpage: User Must Login

Post by Weiry »

Currently we only have what should happen once your logged in and what happens once you log out. It seems we only have 2/3rds of the information so far. My guess is there is something on the login.php page which is causing your session to remain open.

I duplicated your existing logout and index pages and created my own login page.
You will notice that on the test.php i added in some debugging variables within the $_SESSION global.

Once you have logged out of the private stuff, you will constantly be redirected to the login page if you have not already logged in.

Please keep in mind though that you should do far more session checks and authentication checks rather than relying on stored session variables. These variables CAN be spoofed and compromise your secure area.

test.php

Code: Select all

<?php
  //Start session
  session_start();

  //Check whether the session variable SESS_MEMBER_ID is present or not
  if(!isset($_SESSION['login']) || empty($_SESSION['login'])) {
    header("location: login.php");
    //exit();
  }
  print "test.php<br/>";

  if(isset($_SESSION['login']) && $_SESSION['login'] != ''){
        print "<br/><a href='logout.php'>Logout</a><br/>";
        print "<p></p><h1>Logged in, private stuff</h1>";
  }else{
    print "<br/><a href='login.php'>Login</a><br/>";
  }

  print $_SESSION['loggedin'];
?>
login.php

Code: Select all

<?php
session_start();

if(!isset($_SESSION['login']) || empty($_SESSION['login'])){
        if(isset($_POST['button'])){
                $_SESSION['login'] = session_id();
                $_SESSION['loggedin'] = 'yes';
                header("Location: test.php");
        }
}

?>
login.php
<form method="post" action="">
<input type='submit' name='button' value='Login'/>
</form>
logout.php

Code: Select all

<?php
//Start session
session_start();
session_destroy();

//Unset the variables stored in session
unset($_SESSION);
$_SESSION = array();
$_SESSION['loggedin'] = 'no';

//Redirect use to login page
header("location: test.php");
?>
sby247
Forum Newbie
Posts: 8
Joined: Thu Oct 20, 2011 5:50 am

Re: Securing a Webpage: User Must Login

Post by sby247 »

@Weiry...

Pls can I send you the code of the login, page, logout and example of an assigned page so you can see where I gone wrong?? Or should I post it up here cos It seems nt working. I would be grateful for your feedback and help. Thanks so much.
sby247
Forum Newbie
Posts: 8
Joined: Thu Oct 20, 2011 5:50 am

Re: Securing a Webpage: User Must Login

Post by sby247 »

@ Weird and ifying_circus....

Here is the "login.php", "login-exec.php", and "testpage.php"

Login page...

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Cornerstone - Login</title>
<link href="oblogin.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
oblogin {
	background-image: url(images/Plant_growing_on_coins__194479.jpg);
	margin: 15px;
	padding: 15px;
	float: left;
	height: 200px;
	width: 300px;
}
oblogin {
	height: 10px;
	width: 300px;
}
#footer {
	background-color: #CC0000;
	height: 30px;
	margin: 5px;
	padding: 5px;
	color: #FFFFFF;
	width: 930px;
}
#footer {
}
-->
</style>
<link href="oblogin.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.style1 {
	color: #FFFFFF;
	font-weight: normal;
}
.style2 {
	font-family: "Times New Roman", Times, serif
}
.style3 {
	color: #000000
}
.style7 {font-family: "Arno Pro Caption"; font-weight: bold; }
-->
</style>
</head>
<body>
<div id="one"><a href="index.html"><img src="xxxxx.jpg" width="699" height="99" /></a></div>
<div class="style1" id="two">
  <div align="center" class="style3">Welcome to Cornerstone</div>
</div>

<div id="onlogin">
  <form id="loginForm" name="loginForm" method="post" action="login-exec.php">
  <p align="center">Please enter your User ID and <br />
  Password to log in.</p>
  <table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
    <tr>
      <td width="112"><span class="style7">User ID</span></td>
      <td width="188"><input name="login" type="text" class="textfield" id="login" /></td>
    </tr>
    <tr>
      <td><span class="style7">Password</span></td>
      <td><input name="password" type="password" class="textfield" id="password" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="Login" /></td>
    </tr>
  </table>
  </form></div>
 
 
 
    
</div>
<p>&nbsp;</p>
<p>&nbsp;</p>
<div class="style2" id="footer"> Copyrights &copy; Cornerstone 2011-2012. All Rights Reserved.</div>
</body>
</html>




Here is the login-exec.php


Code: Select all

<?php
	//Start session
	session_start();
	
	//Include database connection details
	require_once('config.php');
	
	//Array to store validation errors
	$errmsg_arr = array();
	
	//Validation error flag
	$errflag = false;
	
	//Connect to mysql server
	$link = mysql_connect($hostname, $username, $password);
	if(!$link) {
		die('Failed to connect to server: ' . mysql_error());
	}
	
	//Select database
	$db = mysql_select_db($dbname);
	if(!$db) {
		die("Unable to select database");
	}
	
	//Function to sanitize values received from the form. Prevents SQL injection
	function clean($str) {
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
	}
	
	//Sanitize the POST values
	$login = clean($_POST['login']);
	$password = clean($_POST['password']);
	
	//Input Validations
	if($login == '') {
		$errmsg_arr[] = 'Login ID missing';
		$errflag = true;
	}
	if($password == '') {
		$errmsg_arr[] = 'Password missing';
		$errflag = true;
	}
	
	//If there are input validations, redirect back to the login form
	if($errflag) {
		$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
		session_write_close();
		header("location: login.php");
		exit();
	}
	
	//Create query
	$qry="SELECT * FROM bslogin WHERE username='$login' AND password='".md5($_POST['password'])."'";
	$result=mysql_query($qry);
	
	//Check whether the query was successful or not
	$data=array("fazilah07"=>array("url"=>"insideonbanking.php","password"=>"binti2011"), 
            "norendb7"=>array("url"=>"insideonbanking-1.php","password"=>"yasinmy20")); 

if(isset($_POST['login']) && isset($_POST['password'])) { 
    if($data[$_POST['login']]['password'] == $_POST['password']) { 
       $_SESSION['login'] = $_POST['login'] . " " . $_POST['password']; 
       header('Location: ' . $data[$_POST['login']]['url']); 
    exit();			
		}else {
			//Login failed
			header("location: login.php");
			exit();
		}
	}else {
		die("Query failed");
	}
?>



And here is the test page.....

Code: Select all

<?php
	//Start session
	session_start();
	
	//Check whether the session variable SESS_MEMBER_ID is present or not
	if(!isset($_SESSION['login']) xor (trim($_SESSION['login']) == '')) {
		header("location: login.php");
		exit();
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home</title>
<style type="text/css">
<!--
#header {
	background-color: #000000;
	height: 120px;
	width: 930px;
}
#navigation {
	height: 50px;
	width: 930px;
	padding: 2px;
	margin: 2px;
}
-->
</style>
<script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
<link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.style2 {color: #FFFFFF; font-family: "Times New Roman", Times, serif;}
-->
</style>
<link href="insideon.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.style4 {color: #FF0000; font-size: 36px;}
.style10 {
	font-family: "Times New Roman", Times, serif;
	font-size: 28px;
	font-weight: bold;
}
.style13 {
	color: #000000;
	font-size: 13px;
}
.style14 {font-size: 13px}
.style15 {color: #000000}
.style16 {font-family: "Times New Roman", Times, serif}
.style17 {
	color: #FFFFFF;
	font-weight: bold;
}
-->
</style>
</head>

<body>
<div align="justify"><a href="logout.php">Logout</a>
</div>
<br />
<div id="header"><img src="xxxx.jpg" width="510" height="118" /></div>
</div>

<div id="navigation">
  <ul id="MenuBar1" class="MenuBarHorizontal">
    <li><a href="home.html" class="style2">Home</a> </li>
    <li><a href="myaccount.html">Manage Account</a></li>
    <li><a href="personaldetails.html">Account Holder's Details</a>      </li>
    <li><a href="account.html" class="MenuBarItemSubmenu">Transfers credit</a>
      <ul>
        <li><a href="localtransfer.html">Local </a></li>
        <li><a href="foreign.html">International </a></li>
      </ul>
    </li>
  </ul>
</div>
<div id="body">
  <div id="menu">
    <p align="center" class="style17">Home</p>
  </div> 
  <div class="style4" id="insidebody">
    <p align="right" class="style10"><img src="file:///C|/Users/Kingsberry/Desktop/fazilah.jpg" width="126" height="94" /></p>
    <p class="style10">Welcome Fazilah Binti Ismail! </p>
    <p class="style14"><span class="style13">You are successfully logged in on
        <script type="text/javascript">var d=new Date();
document.write(d);

        </script>
    </span></p>
    <p class="style14">&nbsp;</p>
    <table width="641" height="346" border="1" cellpadding="2" cellspacing="2" bgcolor="#F0F0F0">
      <tr>
       
      <tr>
       
      </tr>
    </table>
    <p class="style14">&nbsp;</p>
  </div>
   <p>&nbsp;</p>
  <p>&nbsp;</p>
  <div class="style16" id="footer"> 
    <div align="center">Copyrights © Cornerstone . All Rights Reserved. </div>
  </div>
</div>
<script type="text/javascript">
<!--
var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
//-->
</script>
</body>
</html>

And here is the logout.php


Code: Select all

<?php
	//Start session
	session_start();
	
	//Unset the variables stored in session
	unset($_SESSION['login']);
	unset($_SESSION['login']);
	unset($_SESSION['login']);


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Logged Out</title>
</head>
<body bgcolor="#CCCCCC">
<h1>&nbsp;</h1>
<p align="center">&nbsp;</p>
<h4 align="center" class="err style3 style5">Thank You for Banking with Standard Alliance Bank.</h4>
<h4 align="center" class="err style1 style4">You have been successfully logged out.</h4>
<p align="center" class="style1"><span class="style2">Click <a href="login.php">here</a> to  continue banking or close the page</span></p>
</body>
</html>



So guys...please is there anywhere i gone wrong in the coding?? If I do, please correct me with the correct codings.

Thanks so much in advance.
Last edited by Benjamin on Fri Oct 21, 2011 2:19 am, edited 1 time in total.
Reason: Added [syntax=php|sql|css|javascript] and/or [text] tags.
Post Reply