Greetings all,

I am working on a website with data I only want logged in users to see. I currently have it where once they have logged in successfully, they can browse the website, and if they are not, they are directed to the login page. Sounds great. However, if they attempt to view a private page a second time, they apparently have a session that allows them to visit. I want to make it where you must login to have a session. How is this done? Here is my code as it stands right now:

The login page:

<?php
session_start();
$_SESSION['loggedin']='1'
?>
//my html code with a login table

I don't think that is where the problem is, I think its in the subsequent pages, which all open with this code:

<?php
session_start();
if ($_SESSION['loggedin']!=1){
header("Location:main_login.php");
exit;
}
if (isset($_GET['logout']))
{
	$_SESSION = array();
	if ($_COOKIE[session_name()])
	{
		setcookie(session_name(), '', time()-42000, '/');
	}
	session_destroy();
	header('Location: main_login.php');
}
?>
//my html code.

Like I said, the first time they try to access the any of these pages it does redirect to the login page, but if they try it a second time, they somehow are allowed in. What am I doing wrong?

You should set $_SESSION='1' only after the successful login not in the beginning of the script.

ok, do I enter that in my login page or the other pages? and can someone point me to an example, i'm kind of a newbie. Just started learning php last week.

Change your login page to something like:

<?php
// start a session (always first thing in a script)
session_start();
// initialize session variable with value for not valid login
$_SESSION['loggedin']='0'
// check for form submission (user clicked on submit button)
if($_POST['submit']) {
// check if username and password are OK (query a database)
// and set some flag if OK (i.e. $is_valid = true;)  else set it to false
// ...
// check the flag
if($is_valid) {
// now set the session
$_SESSION['loggedin']='1'
// and redirect to next page 
header("location:page_for_loged_users.php")
} else {
// if the flag is set to false, user credentials were wrong
// redirect to page with an error or with login form or whatever
header("location:page_for_signup_or_error.php")
}
}
?>
//your html code with a login table

There are of course other ways of doing it like doing it all on one page and when wrong credentials were submitted the html code displays an error otherwise a login form.

Ah, I'm starting to understand I think. I need to make a default session value different from a logged in session value. Unfortunately, I'm having some trouble with your code, getting some errors, but I will keep working on it. But thanks for the info, now I at least know why this is happening. If you (or anyone else) have something that will help speed this up I would greatly appreciate it.

Ok, I'm so close I think. People can't get get a session without logging in. Unfortunately, now people who do log in are still getting a value of '0' instead of '1'. I think my problem now is that it sees the 'submit' in the php code as an undefined index. "NOTICE:Undefined index:submit on line 4". Here is the code as I have it now (I took out the "else" stuff because I already have it where they get told they have an invalid usnername and/or password if they login incorrectly and the else statement was giving me a ton of errors).

<?php
session_start();
$_SESSION['loggedin']='0';
if($_POST['submit']) {
if($is_valid) 
$_SESSION['loggedin']='1';
header("Location:login_success.php");
} 
?>
<html>
<body style="background-color:rgb(240,230,200);font-family:Times;font-size:110%;">
<p style="text-align:center;font-family:Times;font-size:250%"> //welcome info//</p>
<CENTER><img src="//welcome pic//" width="300" height="250"/></Center>
<p style="text-align:center;font-family:Times;font-size:200%"> Please Login</p>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#F0E6c8">
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</body>
</html>

Change line 4 to

if(isset($_POST['Submit']) and !empty($_POST['Submit']))

Your code is stil not OK. The credentials validation part is missing. You must check wheter supplied username exists in the database, and wheter password is correct. If both these conditions are true, you set the login condition ($_SESSION='1'). The flag $is_valid is not necessary it was propsed just for clarity.

The logic baicaly is:
1. set the login condition ($_SESSION='0') to false (or 0 in your case), until you check that the user provided correct credentials
2. check for any input from user (line 4)
3. if input exists check if the credentials are OK
4. if credentials are ok, set the login condition ($_SESSION='1') and redirect the user to authorized page
5. if credentials are not OK, do something elese (error mesage, sign up form...)
6. display the table with the login form

I would like to give you an example but am a bit tight with time so I do not promis anything.

I think its step 3 where I'm stumbling. Here is my code as it stands right now:

<?php
session_start();
$_SESSION['loggedin']='0';
if(isset($_POST['Submit']) and !empty($_POST['Submit'])){
if($is_valid)
$_SESSION['loggedin']='1';
header("Location:login_success.php");
}
?>

BTW sry to be such a pain. I just started learning this stuff last week, and I'm diong it completely on my own. No teacher, no friends, not even a book, just what I can glean on the internet. Mostly I have been learning from w3schools.com, but they are a little scanty on examples, the ones they do have being very basic, and no examples almost of things that don't work that one might intuitively think would work. If you can point me to a reference source I would greatly appreciate it =).

Ok, I have tried every way of saying it I can think of. I even tried "condition"? statements. I keep sending the people who log in successfully back to the login screen. If they login incorrectly they get a message saying so, but they don't get to proceed like they should if they entered it in correctly. Anyone got any ideas?

I have prepared a tutorial with example on how to code a login page. It has been submited as a new thread to the tutorial section. It is not yet there though so I am posting the code here as well. Hope it will help you. It is well commented. Everyone is invited to comment on it and suggest improvements.

<?php
/*
Login script example
- displays a form for entering username and password
- checks wheter username and password exist in database and match
- if no match is found, clears the form and displays an error message
- if exactly one match is found, redirects user to another page

Tip: make page look nicer with some CSS

For this login example you will need working database (mySql used here), and
some test data as per instructions below (or you can use phpmyadmin or similar app)

Test data (2 users):

username 1: misterx
password 1: secretpassword1
hashed password1: (d5f835dbe946b420e1dacde0558078b4eee36745)

username 2: mistery
password 2: secretpassword2
hashed password2: (fd021e83bf64b46a2a7b707441dd167bc43749d4)

Prepare database 'mydatabase' with table 'user' and some test data

1. Use this or similar query to create database 'mydatabase'
CREATE DATABASE `mydatabase` ;

2.create DB user named 'testdbuser' with password 'verysecretdbpassword' and
 granthim privileges
CREATE USER 'testdbuser'@'%' IDENTIFIED BY 'verysecretdbpassword';
GRANT ALL PRIVILEGES ON * . * TO 'testdbuser'@'%'
IDENTIFIED BY 'verysecretdbpassword'
WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0
    MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;

3. Use this or similar query to create table 'users' in database 'mydatabase'
CREATE TABLE `mydatabase`.`users` (
`id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'ID (primary key)',
`username` VARCHAR( 24 ) NOT NULL COMMENT 'Username (max 24 chars)',
`hpassword` CHAR( 40 ) NOT NULL COMMENT 'sha1 hashed password'
) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'Users table';

4. Use this query to insert above test data into the table 'users'
INSERT INTO `users` (`id`, `username`, `hpassword`) VALUES (NULL , 'misterx', '298e6df75f76926af93925e7a34e060ea523a363');
INSERT INTO `users` (`id`, `username`, `hpassword`) VALUES (NULL , 'mistery', '05b68c5b67e2c7a95cc86e4ee26778e5d9c77c6c');
*/

// start session
session_start();

// set session variable that identifies valid user to 0 until user submits
// valid username and passwordusername
$_SESSION['valid_user'] = 0;

// a variable that will hold error message if needed
$msg = '';

// check wheter user has submitted a username and/or password
if(isset($_POST['username']) or isset($_POST['password'])) {

    // if both username and password are submitted and not empty
    if(isset($_POST['username']) and !empty($_POST['username']) and
       isset($_POST['password']) and !empty($_POST['password'])) {

        // asign posted values to variables and trim possible spacess before and
        // after the strings
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);

        // passwords stored in the users database are hashed with sha1 therefore
        // submited password has also be hashed so values can be compared
        $hpassword = sha1($password);

        // prepare database connection
        $conn = mysqli_connect('localhost', 'testdbuser', 'verysecretdbpassword', 'mydatabase')
            or die ('ERROR: Can not connect to the database!');

        // prepare query to select a user with submitted username and hashed
        // submitted password (to check for the match)
        $query  = "SELECT username, hpassword FROM users ";
        $query .= "WHERE username='$username' AND hpassword='$hpassword'";

        // get the result of the query
        $res = mysqli_query($conn, $query);

        // if mysqli_query was successful and if one row was returned from query
        // we have a match, the username and password are OK
        // (if no rows returned username and password did not match, if more than
        // 1 row returned we have entered one user more times which is incorrect
        if($res and mysqli_num_rows($res) == 1) {

            // set session variable that identifies valid user to 1
            $_SESSION['valid_user'] = 1;

            // redirect user to login_success.php page
            header("location:login_success.php");

            //just in case anything goes wrong from here end the script
            die();
        }

        // if no rows are returned username and password did not match
        // (or if more than 1 row returned we have entered one user many times
        // which is incorrect)
        else {

            // again set session variable that identifies valid user to 0
            $_SESSION['valid_user'] = 0;

            // prepare error message
            $msg = 'Please enter correct username and password!';
        }
    }

    // if only username or only password was submitted
    else {

        // again set session variable that identifies valid user to 0
        $_SESSION['valid_user'] = 0;

        // prepare error message
        $msg = 'Please enter correct username and password!';
    }
}
?>
<!DOCTYPE html
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
<title>Login</title>
</head>

<body>

<!-- Form will be submitted to itself -->
<form action="#" method="post">

<p>Please login</p>

<div class="login"><input name="username" type="text" id="username" /></div>

<div class="login"><input name="password" type="password" id="password" /></div>

<div class="login"><input type="submit" name="submit" value="Login"></div>

<!-- Possible error messages will be displayed here -->
<div class="error-message"><p><?php echo $msg ?></p></div>

</form>

</body>

</html>

THANK YOU SO MUCH!!! After a little bit of editing to fit my situation this worked perfectly!! I really appreciate this!

You are welcome.

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.