Show DevBest [PHP] Login & Logout

Obey

You just played yourself.
Nov 23, 2013
250
29
This is the first time I've ever used PHP so forgive me for any errors.
I gathered a simple login and logout script that DOES need access to your database. I've included a db.php file below so if you don't already have one, make one and include the code below inside. There is only HTML in the logout script but it's easy to make a text/password field in the login one.
Includes:
  • SQL injection protection (unintentional rhyming)
  • Checks if all fields are filled in and displays an error if they aren't.
  • Automatically directs to index.php when logged in, change it if you want it to direct somewhere else.
I mean it is only a login and logout script, it is really simple and there's nothing special.

Login:
PHP:
<?php
    session_start();

    if(isset($_POST['login'])) {
        include_once("db.php");
        $username = strip_tags($_POST['username']);
        $password = strip_tags($_POST['password']);
            $error = '';
            if( empty( $username ) )
            {
                $error .= 'You have to enter your username!<br>';
            }
            if( empty( $password ) )
            {
                $error .= 'You have to enter your password!<br>';
            }
            if( $error )
            {
                echo "$error";
                $disablebutton = false;
            }
            else
           
           
               
        $username = stripslashes($username);
        $password = stripslashes($password);
       
        $username = mysqli_real_escape_string($db, $username);
        $password = mysqli_real_escape_string($db, $password);

        $password = md5($password);

        $sql = "SELECT * FROM users WHERE username='$username' LIMIT 1";
        $query = mysqli_query($db, $sql);
        $row = mysqli_fetch_array($query);
        $id = $row['id'];
        $db_password = $row['password'];

        if($password == $db_password) {
            $_SESSION['username'] = $username;
            $_SESSION['id'] = $id;
            header("Location: index.php");
        } else {
            echo "You didn't enter the correct details!";
        }

    }
?>
Logout:
PHP:
<?php
     session_start();
    session_destroy();
     
?>

<html>
<head>
<meta http-equiv="refresh" content="1;url=login.php">
<title>Logout</title>
</head>
</html>
Db.php:
PHP:
<?php
$db = new mysqli('localhost', 'root', 'password', 'db_name');

if ($db->connect_errno > 0) {
    die('Unable to connect to the database [' . $db->connect_error . ']');
}
?>
The checking if you filled in all fields code I got from @Markshall so thank you to him.
This was aimed at people like me who want to use one of these but doesn't know how; I'm sure it will help someone.
 

Obey

You just played yourself.
Nov 23, 2013
250
29
I've seen this code before, on another forum. Exactly the same.
This is the first time I've ever used PHP so forgive me for any errors.
I gathered (not created)
ALSO: This was aimed at people like me who want to use one of these but doesn't know how; I'm sure it will help someone.
I only took this and enhanced it by adding a few features to it for noobs like myself who can't code stuff like this.
 

griimnak

You're a slave to the money then you die
Jul 20, 2013
955
794
PHP:
mysqli_real_escape_string($db, $username);
I didn't even know this was a thing.

For the future, you should use PDO instead of mysqli. And you should learn how to write Object Oriented Code.
cool script though, i guess.
 

griimnak

You're a slave to the money then you die
Jul 20, 2013
955
794
Yeah not trying to be a dick but it would of been better if you were to re create the whole script from scratch, with what you learned from the old one.
because this script looks kinda dated, poor error filtering and it's full of XSS vulns, make sure you strip html tags otherwise people can execute javascript
edit: nevermind you already did
 

RastaLulz

fight teh power
Staff member
May 3, 2010
3,926
3,921
You should never use md5 to hash a password, instead please look into the function that PHP provides.
it's full of XSS vulns, make sure you strip html tags otherwise people can execute javascript
This is very bad advice; whatever the user submitted should remain exactly as is when stored in the database. To prevent against XSS attacks, your template engine should assume that responsibility by applying something like on all variables outputted, unless explicitly told not to. Obviously if you're not using a template engine, you should just wrap everything that came from the user with when echoing it.

With that being said, you must also use prepared statements, otherwise you open yourself up to SQL injections.
 

Obey

You just played yourself.
Nov 23, 2013
250
29
You should never use md5 to hash a password, instead please look into the function that PHP provides.

This is very bad advice; whatever the user submitted should remain exactly as is when stored in the database. To prevent against XSS attacks, your template engine should assume that responsibility by applying something like on all variables outputted, unless explicitly told not to. Obviously if you're not using a template engine, you should just wrap everything that came from the user with when echoing it.

With that being said, you must also use prepared statements, otherwise you open yourself up to SQL injections.
I just used md5 because it's a built in feature of PHP and it's pretty simple.
 

Sledmore

Chaturbate Livestreamer
Staff member
FindRetros Moderator
Jul 24, 2010
5,194
3,901
I just used md5 because it's a built in feature of PHP.

So is password_hash() & password_verify()


 

RastaLulz

fight teh power
Staff member
May 3, 2010
3,926
3,921
I just used md5 because it's a built in feature of PHP.
Just because something is built into PHP doesn't mean you should use it, especially when it comes to security related things (please do some research). MD5 has massive brute forced dictionaries, making it possible to easily convert your average user's password to plain text, defeating the purpose of hashing passwords in the first place.
 

Obey

You just played yourself.
Nov 23, 2013
250
29
Just because something is built into PHP doesn't mean you should use it, especially when it comes to security related things (please do some research). MD5 has massive brute forced dictionaries, making it possible to easily convert your average user's password to plain text, defeating the purpose of hashing passwords in the first place.
Just because something is built into PHP doesn't mean you should use it, especially when it comes to security related things (please do some research). MD5 has massive brute forced dictionaries, making it possible to easily convert your average user's password to plain text, defeating the purpose of hashing passwords in the first place.
So is password_hash() & password_verify()


Wow, should've looked into that more. I'll make it securer next time.
 

griimnak

You're a slave to the money then you die
Jul 20, 2013
955
794
You should never use md5 to hash a password, instead please look into the function that PHP provides.

This is very bad advice; whatever the user submitted should remain exactly as is when stored in the database. To prevent against XSS attacks, your template engine should assume that responsibility by applying something like on all variables outputted, unless explicitly told not to. Obviously if you're not using a template engine, you should just wrap everything that came from the user with when echoing it.

With that being said, you must also use prepared statements, otherwise you open yourself up to SQL injections.
Well said. Ultimately that's what I meant, I just didn't wanna throw anything about template engines in there because i figured this is purely just a login script
 

GarettM

Posting Freak
Aug 5, 2010
833
136
This is horrid at least document your work bro :-(
PHP:
<?php

/**
* Create session if session does not exist.
*/
if(!session_id())
{
    session_start();
}

/**
* If user has submitted a login form
*/
if(isset($_POST, $_POST['login']))
{
    /**
    * include our database file
    */
    require( dirname(__FILE__) . '/database.php' );
  
    /**
    * set our username and password variable
    */
    $username = strip_tags($_POST['username']);
    $password = strip_tags($_POST['password']);
  
    /**
    * set our error variable
    */
    $error = false;
  
    /**
    * check our username variable and make sure it contains only alphanumeric characters
    */
    if(!ctype_alnum($username) || empty($username))
    {
        /**
        * The username was not alphanumeric or the username was left empty.
        * set a generic error so hackers/smart people don't guess.
        */
        $error = "Username or Password do not match.";
    }
  
    /**
    * check our password variable and make sure it contains only alphanumeric characters.
    */
    if(!ctype_alnum($password) || empty($password))
    {
        /**
        * The password was not alphanumeric or the password was left empty.
        * set a generic error so hackers/smart people don't guess.
        */
        $error = "Username or Password do not match."
    }
  
    /**
    * check to see if our error variable is set
    */
    if(!is_null($error) || isset($error))
    {
        /**
        * Do something with the error message for know we will print it to the page
        */
        echo htmlspecialchars($error, ENT_COMPAT, 'ISO-8859-1', true);
    }
    /**
    * error was not set so we can continue.
    */
    else {
        /**
        * strip slashes from username and password.
        */
        $username = stripslashes($username);
        $password = stripslashes($password);
      
        /**
        * make username and password variables mysqli string safe.
        */
        $username = mysqli_real_escape_string($database, $username);
        $password = mysqli_real_escape_string($database, $password);
      
        /**
        * encrypt password.
        * Note: NEVER EVER USE MD5, Please use crypt
        */
        $password = md5($password);
      
        /**
        * our database query
        */
        $sql_query = sprintf("SELECT * FROM users WHERE username='%s' LIMIT 1", $username);
      
        /**
        * run our database query and collect our result in the fallowing variables
        */
        $database_query = mysqli_query($database, $sql_query);
        $database_row    = mysqli_fetch_array($database_query);
      
        if($password == $database_row['password'])
        {
            /**
            * our encrypted password matched the one we have in our database continue.
            * also store our users information.
            */
            foreach($database_row as $key => $value)
            {
                $_SESSION['account'][$key] = $value;
            }
            // redirect or do something else.
            header("Location: account.php");
        } else {
            /**
            * The username didn't match the username, generic error time.
            */
            $error = "Username or Password do not match.";
            exit; // exit or redirect.
        }
    }
}
was that so hard?
 

griimnak

You're a slave to the money then you die
Jul 20, 2013
955
794
This is horrid at least document your work bro :-(
PHP:
<?php

/**
* Create session if session does not exist.
*/
if(!session_id())
{
    session_start();
}

/**
* If user has submitted a login form
*/
if(isset($_POST, $_POST['login']))
{
    /**
    * include our database file
    */
    require( dirname(__FILE__) . '/database.php' );
 
    /**
    * set our username and password variable
    */
    $username = strip_tags($_POST['username']);
    $password = strip_tags($_POST['password']);
 
    /**
    * set our error variable
    */
    $error = false;
 
    /**
    * check our username variable and make sure it contains only alphanumeric characters
    */
    if(!ctype_alnum($username) || empty($username))
    {
        /**
        * The username was not alphanumeric or the username was left empty.
        * set a generic error so hackers/smart people don't guess.
        */
        $error = "Username or Password do not match.";
    }
 
    /**
    * check our password variable and make sure it contains only alphanumeric characters.
    */
    if(!ctype_alnum($password) || empty($password))
    {
        /**
        * The password was not alphanumeric or the password was left empty.
        * set a generic error so hackers/smart people don't guess.
        */
        $error = "Username or Password do not match."
    }
 
    /**
    * check to see if our error variable is set
    */
    if(!is_null($error) || isset($error))
    {
        /**
        * Do something with the error message for know we will print it to the page
        */
        echo htmlspecialchars($error, ENT_COMPAT, 'ISO-8859-1', true);
    }
    /**
    * error was not set so we can continue.
    */
    else {
        /**
        * strip slashes from username and password.
        */
        $username = stripslashes($username);
        $password = stripslashes($password);
     
        /**
        * make username and password variables mysqli string safe.
        */
        $username = mysqli_real_escape_string($database, $username);
        $password = mysqli_real_escape_string($database, $password);
     
        /**
        * encrypt password.
        * Note: NEVER EVER USE MD5, Please use crypt
        */
        $password = md5($password);
     
        /**
        * our database query
        */
        $sql_query = sprintf("SELECT * FROM users WHERE username='%s' LIMIT 1", $username);
     
        /**
        * run our database query and collect our result in the fallowing variables
        */
        $database_query = mysqli_query($database, $sql_query);
        $database_row    = mysqli_fetch_array($database_query);
     
        if($password == $database_row['password'])
        {
            /**
            * our encrypted password matched the one we have in our database continue.
            * also store our users information.
            */
            foreach($database_row as $key => $value)
            {
                $_SESSION['account'][$key] = $value;
            }
            // redirect or do something else.
            header("Location: account.php");
        } else {
            /**
            * The username didn't match the username, generic error time.
            */
            $error = "Username or Password do not match.";
            exit; // exit or redirect.
        }
    }
}
was that so hard?
Now that's what I call an "improved" version
 

Users who are viewing this thread

Top