user1142202
user1142202

Reputation: 23

How to make a secure session with php and mysql?

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');
}

?>

Upvotes: 2

Views: 3720

Answers (1)

Dipu Raj
Dipu Raj

Reputation: 1884

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.

Upvotes: 2

Related Questions