2

I have tried a session.php script which runs at the head of each page in my website to verify that the user has logged in before they can browse the site. However, now the process_login script won't load the secure landing page and it just reloads to the login page. I believe that my secure session is not being set correctly. Can someone further explain how this works to me?

This is the script, process_login, which executed when a user clicks login:

<?php

// Initialize session
session_start();

// Require database connection settings
require('config.inc');

// Retrieve email and password from database
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string(md5($_POST['password']));
$query = "SELECT * FROM $table WHERE email='$email' AND password='$password' LIMIT 1";
$result = mysql_query($query);

// Check email and password match
if(mysql_num_rows($result)) {
        // Set email session variable
        $_SESSION['email'] = $_POST['email'];
        // Jump to secured page
        header('Location: home.php');
}
else {
            // Jump to login page
            header('Location: index.php');
}

?>

and this is the session.php script which is in the head of each page that requires a user to be logged in:

<?php

if (isset($_SESSION['email']) == 0) {
    // Redirect to login page
    header('Location: index.php');
}

?>
9
  • 2
    Can we see what you've tried? Commented Jan 11, 2012 at 2:34
  • You should show us some code. Commented Jan 11, 2012 at 2:34
  • When the process_login script is called, the user is by definition not yet logged in. So you should not run the verify/redirect code during process_login. Commented Jan 11, 2012 at 2:36
  • hey guys - i asked this guy to post his question on SO, but he's never used it before. i'm just vouching that he's a real person with a real problem and not some fly-by-night :) Commented Jan 11, 2012 at 2:37
  • 2
    but can we trust you @Jason ?? :-) Commented Jan 11, 2012 at 2:39

1 Answer 1

2

You need to include the code

session_start();

in the your file session.php to access your session variables

Or you should make sure that session auto start is enabled on your php configuration.

Sign up to request clarification or add additional context in comments.

3 Comments

but if i have it start a session on each new page will that mess something up?
Dipu raj is correct. Remember, PHP is stateless which is why you need sessions in the first place. You MUST call session_start() on every page load before you access/ser ANY session variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.