Solved

PHP - Session - log in

Posted on 2009-07-11
5
774 Views
Last Modified: 2013-12-13
I have a login html form, which logs in a user using a php script which creates a session (code below).  There is an if else statement in the code that says if the login information is incorrect - then prompt the user to log in with correct information (or register - also on the same html form).  Else - create the session variables for username and password - and go on to the next page (admin.php).
On the admin.php script - the first thing that i'm doing is starting the session and checking the variables - that they are set.  (Code below the login script).
However - I notice that I can still access the page, even when i'm not in a session.  Any ideas on how to fix this?

Also - I have a couple of other pages, where I need to set up the same deal.  How can this be done on an .html page?

Many thanks in advance for your help.

//login script
<?php
session_start();
if (empty($_POST['username']) || empty($_POST['password'])) {
	$error = "<p>You must enter a username and password.  Click <a href='logininfo.html'>here</a> to return to the previous page.</p>";
}
else if (strlen($_POST['password']) < 6 || strlen($_POST['password']) > 8) {
	$error = "<p>Your password must be between 6 and 8 characters.  Click <a href='logininfo.html'>here</a> to return to the previous page.</p>";
}
else {
if(isset($_POST['username'])){$username = $_POST['username'];}
if(isset($_POST['password'])){$password = $_POST['password'];}
 
$connection = mysqli_connect("localhost", "username", "password", "databasename");
$query = "SELECT * FROM newuser WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($connection, $query);
 
if (!(mysqli_num_rows($result) > 0)) {
	$error = "<p>Incorrect Login Information.  Click <a href='logininfo.html'>here</a> to return to the previous page.</p>";
}
else 	{$_SESSION['username'] = "$username";
	$_SESSION['password'] = "$password";
	header('Location:admin.php');
}
 
mysqli_close($connection);
}
?>
<!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>PHP Login Script</title>
</head>
<body>
<font color='#a3b9cb'>
<h1 align="center">Log In</h1>
<?php 
echo $error;
?>
</body>
</html>
 
 
 
//admin.php script
<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['username']=="") {
	header("Location: logininfo.html");
}
else {
?>
<!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>Admin</title>
</head>
<body>
<font color='#a3b9cb'>
<?php
	echo "<h1 align='center'>Welcome to the Administrators Page</h1>";
	echo "<table align='center' bgcolor='#333333' border='2' width='800'cellpadding='2' cellspacing='2'>";
	echo "<tr><td align='center'>Please select a link below:</td></tr>";
	echo "<tr><td><a href='requestform.html'>Display Records</a></td></tr>";
	echo "<tr><td><a href='addentry.html'>Insert A Contact</a></td></tr>";
	echo "<tr><td><a href='#'>Modify an existing record</a></td></tr>";
	echo "<tr><td><a href='#'>Delete a record</a></td></tr>";
	echo "<tr><td><a href='logout.php'>Log Off</a></td></tr>";
	echo "</table>";
}
?>
</body>
</html>

Open in new window

0
Comment
Question by:techlinden
  • 3
  • 2
5 Comments
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 500 total points
ID: 24830465
>> even when i'm not in a session

How do you know you are not in a session? How do you log out? Did you delete the session cookie?

>> How can this be done on an .html page?

It can't (except for using javascript, which can be disabled). You must use .php files to validate the session.
0
 

Author Comment

by:techlinden
ID: 24830491
Ah - could it be my log out page not running correctly?
Below is my logout.php page.

So all of my pages should be php pages if I want to validate the session, correct?  With the exception of my html form page which allows the user to log in.  Is that right?
<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['username']=="") {
	session_unset();
	session_destroy();
}
?>
<!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>Administrator PHP Script</title>
</head>
<body>
<font color='#a3b9cb'>
<h1 align="center">Log In</h1>
<?php
echo "<p>You have successfully logged out!</p>";
echo "<p>Please click <a href='logininfo.html'>here</a> to return to the Login Page.</p>";
?>
</body>
</html>

Open in new window

0
 
LVL 39

Assisted Solution

by:Roger Baklund
Roger Baklund earned 500 total points
ID: 24830642
>> So all of my pages should be php pages if I want to validate the session, correct?  

Yes.
>> With the exception of my html form page which allows the user to log in.  Is that right?

Yes, any page that does NOT need to be protected can have .html extension.

if (!isset($_SESSION['username']) || $_SESSION['username']=="") {

Here you are only destroying the session if $_SESSION['username'] is NOT set or if it is blank. Remove the if() statement, execute session_unset() and session_destroy() regardless of the existence of/value of $_SESSION['username'].
0
 

Author Closing Comment

by:techlinden
ID: 31656993
That did it!  I really appreciate the help!
One quick question - if i'm not in a session - i'm unable to access certain pages - it just brings me directly to the login page (via a header).  How can I create a message that says (you are not logged in) - and which page does it go on - the login page?  Or the page that is directing me back to the login page?

Thanks again
0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24830827
>> How can I create a message that says (you are not logged in)

Put a parameter in the redirect url, and check for this parameter on the target page. In this case the login page should be a .php page, so that yu can test for the parameter:

if (!isset($_SESSION['username']) || $_SESSION['username']=="") {
        header("Location: logininfo.php?msg=notloggedin");
        exit;
}

..and in logininfo.php fetch it like this:

<?php
  if(isset($_GET['msg']) and $_GET['msg']=='notloggedin')
    echo '<p style="color:red">You need to log in before you can access this page!</p>';
?>

I inserted an "exit;" after the redirect. This is good practice, otherwise the rest of the protected page is executed before the actual redirect is executed. You used an else-clause to prevent this, this is easy to forget. When using exit the else-clause is not needed.
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
str_replace not working in php script 4 31
Download tables into separate sheets 3 28
ebay devID, appID, certID, userToken 2 28
website maintenance mode 1 17
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question