0

I'm having issues with a simple login system that I'm trying to create. Here is my setup:

index.php

<?php if(!isset($_SESSION['username'])){
session_start();
//present login form with action=login.php
} else {
//display actual page
}
?>

login.php

<?php
if(!empty($_SESSION['username'])){
    echo $_SESSION['username'];
} else {
$username=$_POST['username'];
$password=sha1($_POST['password']);
$link=mysqli_connect("localhost","root","password","database",3306,"/tmp/mysql.sock");
$query="SELECT * FROM login WHERE `name`='".$username."' AND `passwordhash`='".$password."' LIMIT 1";
$result=mysqli_query($link,$query);
if(mysqli_num_rows($result)==1){
            session_start();
    $_SESSION['username']=$username;
    $row=mysqli_fetch_assoc($result);
    $_SESSION['firstname']=$row['firstname'];
    $_SESSION['lastname']=$row['lastname'];
    echo "Username: ". $_SESSION['username']." Name: ".$_SESSION['firstname']." ".$_SESSION['lastname']; //this is just here as POC. If I redirect to index.php (using header()), it shows the login form (claims $_SESSION['username'] is unset).
}
}
?>

Once I log in, it shows my username and first and last names just fine on login.php (not a database problem). But if I redirect to index.php, it shows the login form immediately. What's the issue? EDIT: Even after adding session_start() to login.php, the same outcome results.

2
  • 1
    You must also call session_start() on login.php. Commented Dec 17, 2012 at 1:51
  • 1
    Call session_start(); before you use $_SESSION Commented Dec 17, 2012 at 1:51

1 Answer 1

2

Make session_start() the very first line of your file it must be included in all files that use session variables

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

3 Comments

Thanks! I hadn't realized it needed to be called in every single file that uses session variables - it seemed to me that the session would endure regardless of file. Thanks again.
Glad I could help make sure to check this answer if it solved your problem
I will as soon as it lets me. I still have 5 minutes until I can mark an answer.

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.