thedigicraft / Atom.CMS

Atom.CMS
56 stars 52 forks source link

Admin Login, Header, Session problem #43

Open Tearstar opened 10 years ago

Tearstar commented 10 years ago

I have been following the video series and I have finished video 28 and am having an issue with the admin login between sessions and the header.

If I have the code of login.php like so:

session_start();

// Connect to Database
include('../config/connection.php');

if($_POST) {
    $query = "SELECT * FROM users WHERE email = '$_POST[email]' AND password = SHA1('$_POST[password]')";
    $result = mysqli_query($dbc, $query);

    if(mysqli_num_rows($result) == 1) {
        $_SESSION['username'] = $_POST['email'];
        header('Location: index.php');
    }
}

and the code of index.php like this

if(!isset($_SESSION['username'])) {
    header('Location:login.php');
}

session_start();

and I try logging in, nothing happens but the redirect from index.php works . . . However if I change the code of index.php to look like so:

session_start();

if(!isset($_SESSION['username'])) {
    header('Location:login.php');
}

the login works and sends me to index.php, but index.php will not redirect when I just goto the admin folder.

I ran a small bit of debug code and got an error about the header already being sent and I did some google searching and saw some people having this issue in other situations and their solution had something to do with the utf8 encoding of their code.

Can you elaborate on this, figure out a solution, or possibly a workaround or something?

I can't progress further until I get this resolved.

dbashby commented 10 years ago

I have just checked the code for admin/login.php, I have the following <?php

session_start();

# Database connection here
require('../config/connection.php');

if($_POST){
    $q = "SELECT * FROM users WHERE email = '$_POST[email]' AND password = SHA1('$_POST[password]')";
    $r = mysqli_query($dbc, $q);

    if (mysqli_num_rows($r) == 1) {

        $_SESSION['username'] = $_POST['email'];
        header('Location: index.php');

    }

}

?> </code

creptor commented 8 years ago

The default parameter session_start() tells the server to fetch the user data from the cookies of the web browser, so to use all the $_SESSION variables you must place that code just before any page.

So in this case, you must place a session_start() before any $_SESSION and inside of index.php and login.php.

PD: the cookies don't store data, well sometimes. They just let the server know witch data has ben set for each user. ($_SESSION['password'] is not stored in the web browser, but a identifier in the cookies will let the server know that he has a password enabled.)