How to create a very simple username - password login in PHP?

24,788

Solution 1

1, You're missing session_start() in index.php. Add it and you should be able to see 'Hello world'

2, Replace your line with "Access granted!" with a redirect:

header('Location: index.php');
exit;

3, You can definitely store credentials in a cookie, but you should always hash and salt the password. Here is a good article about password hashing.

Solution 2

Better way of doing things: Check for the session variable in the index.php and redirect if it is not set. Something like this

session_start();
if (!isset($_SESSION['auth']) || $_SESSION['auth'] != 1) {
   header('Location: login.php');
   exit();
}
echo 'Hello'; 

In the login.php, after successful authentication, redirect to index.php and do the echo there.

session_start();
if( $name == "<some name>" && $pass == "<some password>" )
{
// Authentication successful - Set session
   $_SESSION['auth'] = 1;
   setcookie("username", $_POST['name'], time()+(84600*30));
   header('Location: index.php');
   exit();
}
else {
  echo "ERROR: Incorrect username or password!";
}

session_start() should come before any content is echoed to the browser.

Solution 3

You should:

  1. always try to call session_start() as early as possible - "To use cookie-based sessions, session_start() must be called before outputing anything to the browser."

  2. check whether $_POST['name'] isset before doing $name = $_POST['name'];. You can do:

    $name = isset($_POST['name']) ? $_POST['name'] : '';
    
  3. store the username directly in $_SESSION so that cookie holds only PHPSESSID and no data that could be replaced / abused by the end users:

    $_SESSION['user'] = 'John';
    
  4. try to redirect the user to index.php to see the immediate result of changing the session:

    header('Location: index.php');
    exit;
    

So this is how it could look like:

<?php
session_start();
if (empty($_SESSION['user'])) {

    $name = isset($_POST['name']) ? $_POST['name'] : '';
    $pass = isset($_POST['pass']) ? $_POST['pass'] : '';

    if ($name != '' || $pass != '')
    {
        if ($name === '')
            die("ERROR: Please enter the username!");

        if ($pass === '')
            die("ERROR: Please enter the password!");

        if ($name == "test" && $pass == "test") {

            // authentication successful, save username in session:
            $_SESSION['user'] = 'John';

            // redirect to index.php to welcome the logged in user:
            header('Location: index.php');
            exit;
        }
        else {
            die("ERROR: Incorrect username or password!");
        }
    }

    // no submitted data, display form:
    ?>
        <html>
        <head></head>
        <body>
            <center>
            <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
            Username: <input type="text" name="name" value=""><br>
            Password: <input type="password" name="pass"><br>
            <input type="submit" value="Log In">
            </form>
            </center>
        </body>
        </html>
    <?php
}
else {
    // info about current user is stored in session, welcome this user:
    echo "hello " . $_SESSION['user'];
}
?>

Solution 4

How do I get it so I can reload index.php and it displays 'hello'?

Remove the else, so it will always display the "hello":

if($_SESSION['auth'] != 1) {
    require('login.php');
}
// Either way always print.
echo "hello";

How can I get login.php to auto-load index.php on a successful authentication so I can get it to that "hello"?

Replace echo "Access granted!"; with header('Location:index.php');

Later, would using a cookie to store the user's submitted login data (so they don't have to refill the form to restore their session) have any potential problems?

As long as are using this as a way to autofill the username only. and require the users to enter their password every time. otherwise a user can set his username cookie to "admin" or some other user.

Solution 5

Use this to redirect to index.php (I hope it answers your #1 and #2)

if( $name == "<some name>" && $pass == "<some password>" )
{
    // Authentication successful - Set session
    session_start();
    $_SESSION['auth'] = 1;
    setcookie("username", $_POST['name'], time()+(84600*30));
    //echo "Access granted!";
    header("Location: index.php");
    die('');
}

You are using cookies to store the username directly. That is not a great option. What if a user modifies the cookies, to read some other username? Instead use $_SESSION['..'] Like this:

$_SESSION['user']=$_POST['name'];

and then later on,

if (isset($_SESSION['user']))
    echo "Hello, " . $_SESSION['user'];
Share:
24,788
Hamster
Author by

Hamster

Updated on July 09, 2022

Comments

  • Hamster
    Hamster almost 2 years

    index.php

    <?php
    if( $_SESSION['auth'] != 1 ) {
        require( 'login.php' );
    }
    else {
        echo "hello";
    }
    ?>
    

    login.php

    <?php
    $name = $_POST['name'];
    $pass = $_POST['pass'];
    
    if( isset($name) || isset($pass) )
    {
        if( empty($name) ) {
            die ("ERROR: Please enter username!");
        }
        if( empty($pass) ) {
            die ("ERROR: Please enter password!");
        }
    
    
        if( $name == "<some name>" && $pass == "<some password>" )
        {
            // Authentication successful - Set session
            session_start();
            $_SESSION['auth'] = 1;
            setcookie("username", $_POST['name'], time()+(84600*30));
            echo "Access granted!";
        }
        else {
            echo "ERROR: Incorrect username or password!";
        }
    }
    
    
    // If no submission, display login form
    else {
    ?>
        <html>
        <head></head>
        <body>
        <center>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        Username: <input type="text" name="name" value="<?php echo $_COOKIE['username']; ?>">
        <p />
        Password: <input type="password" name="pass">
        <p />
        <input type="submit" name="submit" value="Log In">
        </center>
        </body>
        </html>
    <?php
    }
    ?>
    

    So, as I'm still learning PHP, there's a few things I'm trying to figure out now:

    • How do I get it so I can reload index.php and it displays 'hello'?
    • How can I get login.php to auto-load index.php on a successful authentication so I can get it to that "hello"?
    • Later, would using a cookie to store the user's submitted login data (so they don't have to refill the form to restore their session) have any potential problems?

    Help appreciated.

  • Hamster
    Hamster over 13 years
    I meant display 'hello' after successful authentication.