create a simple PHP login / logout system

13,767

Solution 1

I found some errors in your code, all coming down to the same point: You cannot send any custom headers after you have began outputting other data.

Where have you done this?

Here:

echo "<script>alert(' FOUND!')</script>";
session_start();//session_start() sends a cookie to the clients machine. 
//How are cookies sent to clients browsers? Through headers.

And here:

setcookie("login_email", $_SESSION['login_email'], time()+60*60*24);
setcookie("login_pwd", $_SESSION['login_pwd'], time()+60*60*24);
header('Location:index.php');

Personally, I think your code is a complete mess. Because I have nothing better to do, I'll re-write it for you, explaining each step as I go along.

Let's begin:

So the first thing you want to work on is your text file, which stores all the user details.

Instead of using plain lines or whatever, we should use JSON to split users details, from user to user.

So here's what the text file will look like with two users in it:

{"navnav":{"username":"navnav","pass":"deb1536f480475f7d593219aa1afd74c"},"user2":{"username":"user2","pass":"deb1536f480475f7d593219aa1afd74c"}}

Notice how I've also used the username as keys too and how I've hashed the password. So we call this file user.txt and store it somewhere safe.

Now, for the login page, we shall simply get the data through the POST method, compare it, set sessions and tell the user to go somewhere else (redirect them).

session_start();//need to start our session first, of course

//check if any login data has been posted our way
if ( isset($_POST['login']) && !empty($_POST['username']) && !empty($_POST['password']) )
{

//assign input data to temp vars
$username = $_POST['username'];
$password = md5($_POST['password']);//notice how I hash the password 

// get the data fro the text file
$userData = file_get_contents('path to your text file');

//decode the json data to an assoc array 
$userData = json_decode( $userData , true );

//check if the user exists
if ( array_key_exists( $username , $userData ) === false )
{

echo 'the username '.$username.' is invalid.';//notify the user
exit();//bye bye

}//end of user does not exist

//so now we know the user name exists (because we've got to this line)
//we shall compare with the password

if ( $userData['$username']['password'] !== $password )
{

echo 'Your password is incorrect';//notify the user
exit();//bye bye


}//end of incorrect password
else
{

//time to set sessions and stuff
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;

//send the redirect header
header('Location: index.php');
exit();

}//end of password is correct


}//end of login data has been sent

That's all your login code, but you need your html form setup correctly for the right things to be posted with the right names. So use this html form:

<form action="login.php" method="post" name="login" target="_self" id="login">
  <p>
    <label for="username">Username</label>
    <input type="text" name="username" id="username" />
  </p>
  <p>
    <label for="password">Password</label>
    <input type="text" name="password" id="password" />
  </p>
</form>

That's your login page completely sorted.

Now for your index.php:

As you did before, check if the user is logged in and throw the status is in a var:

session_start();//resume your session (if there is one) or start a new one

//set default user status
$userStatus = false;

if ( isset($_SESSION['username']) && isset($_SESSION['password']) )
{

$userStatus = true;

}//end of user is logged in

For your HTML login/logout:

<li><a href="index.php">Home</a></li>
<li><a href="register.php">Register</a></li>

<?php
if ($userStatus === true){
echo "<li><a href='logout.php'>Logout</a></li>";
}
else{
echo "<li><a href='login.php'>Login</a></li>";
}
?>
<li><a href="#"> Link 4</a></li>

And there you have it.

Let me know if you have any problems.

One more thing:

This is far from secure. Why? You're using text files, you're using text files and you're using text files.

EDIT:

To separate the JSON data by user, simply edit the text file manually (see my comment).

Or you could just paste this into your text file:

{"navnav":{"username":"navnav","pass":"deb1536f480475f7d593219aa1afd74c"},
"user2":{"username":"user2","pass":"deb1536f480475f7d593219aa1afd74c"}}

Do you see how there is no \n in the above? Because I just created a new line manually (by just hitting enter). \n will make the JSON code invalid, so that's why you should avoid it. This method just means if you have to create new users, and you need a new line for each user, then you will have to do it manually.

Solution 2

Actually your script does the opposite of what you are probably intended to:

strcmp does compare both parameters, but it does not return a boolean value.

First thing to do 'd be to change that line to:

if ($_REQUEST['email'] === $lineArray[2] && $_REQUEST['pwd'] === $lineArray[4]) {

Solution 3

First of all, never send a header after some output has occurred, i.e. when you do echo "<script>alert(' FOUND!')</script>"; this is considered output and a header will be generated by PHP and your header line later on will be ignored.

Try using header without any output being sent first, this should fix the redirect problem.

As far as why the session information is wiped, try the following line on the redirect:

header('Location:index.php?'.SID);

It shouldn't be required but its worth giving it a shot.

Share:
13,767
KSM
Author by

KSM

Updated on June 04, 2022

Comments

  • KSM
    KSM almost 2 years

    This is for an assignment, however ive done a lot on my part to research but i feel like ive reached a wall. I need to create a page where the user can go to sign in (login.php), once they're signed in they're redirected to the index page. The link they clicked to login should be replaced with a logout link.

    however with all this noted, first things first i do get into the session part and ive echoed the variables and retrieved them however it doesnt do the redirect to the index.php also when i manually click to the index.php after logging the session variables are empty. what am i doing wrong here???

    so this is my php code in the login.php

              $found = false;
              //read the read.txt until the end of file
              while(!feof($inputFile) && $found == false)  
              {
    
                $line = fgets($inputFile);  
                // replace the special charater within the lines by there proper entity code
                $lineArray = preg_split("/\,/", (string)$line);
    
                if(strcmp($_REQUEST['email'],$lineArray[2])  && strcmp($_REQUEST['pwd'],$lineArray[4]))
                {
                            $found = true;
                            echo "<script>alert(' FOUND!')</script>";
                            session_start();
                            $myuseremail=$_REQUEST['email'];
                            $mypassword= $_REQUEST['pwd'];
    
                            $_SESSION['login_email']=$myuseremail;
                            $_SESSION['login_pwd']=$mypassword;
                            setcookie("login_email", $_SESSION['login_email'], time()+60*60*24);
                            setcookie("login_pwd", $_SESSION['login_pwd'], time()+60*60*24);
                            header('Location:index.php');
                }
              }
              fclose($inputFile);
    

    and then in my index.php i contain this code before the body of my html

        <?php
    
          session_start();
       if(isset($_SESSION['login_email']) && isset($_SESSION['login_pwd']))
       {
        $user_check=true;
        echo $_SESSION['login_email'];
       }
       else
       {
        $user_check=false; 
       }
    
    ?>
    

    within the index.php i also have this code lined in for my links

         <li><a href="index.php">Home</a></li>
     <li><a href="register.php">Register</a></li>
    
     <?php
    
    if ($user_check){
                     print "<li><a href='logout.php'>Logout</a></li>";
     }
     else{
     print "<li><a href='login.php'>Login</a></li>";
     }
     ?>
                <li><a href="#"> Link 4</a></li>
    
    • Marc B
      Marc B over 11 years
      Oh. Goodie. storing passwords/usernames in plaintext cookies. That's secure...
    • KSM
      KSM over 11 years
      @MarcB yeah good thing you noticed that, but like i said earlier its an assignment, it required a txt file and not database. I wouldn't have done it in a txt if it was required.
    • KSM
      KSM over 11 years
      @JohnConde if someone answers i would love to accept them.
    • jaydeep namera
      jaydeep namera over 10 years
      Login and logout in php using session : allitstuff.com/login-and-logout-in-php-using-session
  • KSM
    KSM over 11 years
    Hey Mash, i changed my code to the following but didnt work. I removed the echo and places the line of code given.
  • KSM
    KSM over 11 years
    Hey Lars i originally had the line of code you mentioned above however it was not comparing it the way i wanted it too, once i changed the == to strcmp it checked for the values.
  • Lars Knickrehm
    Lars Knickrehm over 11 years
    Please combine this answer and mine. strcmp returns 0 on equality, so in you case users should be able only if their credentials are wrong!
  • KSM
    KSM over 11 years
    @LarsKnickrehm i re-placed the line you gave me now and when i place the right password and right email it doesn't seem to go inside the if, i also placed "prints" and both $_REQUEST and $lineArray contain the same values. Whats wrong with this ???
  • KSM
    KSM over 11 years
    -this is the array: kay -this is the array: 123456789 -this is the request: kay -this is the request: 123456789 -
  • KSM
    KSM over 11 years
    thanks for the suggestion im going to try this out right now!
  • KSM
    KSM over 11 years
    However the assignment was based on a txt file, also the way you did the JSON, im not sure if its applicable, for the assignment part its written "open a text file, members.txt and write all the user registration information into the file (the formatting is up to you). Multiple registrations should be possible and each new registration should be separated by a blank line." can JSON be formatted to take new lines as a user???
  • Admin
    Admin over 11 years
    If it says "the formatting is up to you", then don't worry, it should be fine.
  • Admin
    Admin over 11 years
    Is this for a UNI assignment or school/college assignment? Just curious.
  • Admin
    Admin over 11 years
    Woops, I missed something. Yes, you can separate the users with blank lines, but just make sure you don't place any other characters in there. Don't use \n to make the lines. Simply go into notepad or whatever text editor, and manually separate the users data (just hit the enter key) where appropriate.
  • KSM
    KSM over 11 years
    but it says should be separated by a blank line how can i do that without the \n ????
  • Admin
    Admin over 11 years
    @user1090656 by simply doing it manually. Go into the text file, and separate them yourself. See my edit.