Create a Secure Login Script in PHP and MySQL

Nowadays, with more and more stories of cracking in the news, developers are looking for the best ways of securing their sites. If your site has a member system, it could be at risk from being cracked and your users' data could be compromised. This guide will show you one attempt at making a secure login using PHP. The code is as good as we can make it, but security and especially encryption are complex subjects that are changing all the time, and we can't claim to have the entire field mastered. Therefore we may have missed a few tricks in our code. If we have, please let us know and we'll try to incorporate any improvements into what we have.

Writing a login system is a complex topic and not something to be undertaken by those who are not intimately familiar with a wide variety of security topics. The login system presented here is to be used for educational purposes, not a production environment. If you need a login system for a production environment, please locate a prepacked and vetted system. There are several listed in the Warnings section at the end of this article.

Following this guide will help guard against many types of attack that crackers can use to gain control of other users' accounts, delete accounts and/or change data. Below is a list of possible attacks this guide tries to defend against:

The approach is to use a mixture of data filtering, encryption and other methods to make the lifes of the bad guys just that little bit more difficult.

We're continually trying to improve this script. The very latest version of the code is available from github. There may be some differences between the code you download in this way from the code quoted in this article. You should also know that we have made no attempt to make the HTML pages output by the application look at all pretty.

You may also notice that we do not close PHP tags in files containing only PHP code. This is in line with most code formatting recommendations.

Finally, you need to know that we ask you to create all the application's non-HTML files in various directories within the application's root directory. The easiest way to get the correct directory structure is to download the latest code by following one of the links above.

Please feel free to use this application as a basis for your own implementation, but don't use it as any kind of example of good coding practice!

Things You'll Need

As we will be using the mysqli_* set of PHP classes to access our MySQL database you will need the following versions of PHP and mySQL.

  • PHP version 5.3 or later
  • MySQL version 4.1.3 or later

You will also need, of course, a web server configured to use PHP, to host your pages. This will most likely be your Web Host's web server, unless you are hosting the site yourself.

To check the version of PHP and MySQL on your server use the phpinfo(); function.


Configure Your Server

  1. Install a Web Server, PHP and MySQL on your server.
    <b/>Most web hosting services will have PHP and MySQL already installed. You will just have to check they have the most recent versions of PHP and MySQL for this guide to work. If they don't have at least PHP5.3 and MySQL5 you might like to ask a few questions about their commitment to security. Keeping your software up-to-date is a part of the security process.

    If you have your own server or computer, you should install the required software in the normal way for your system. Generally speaking, if you are not going to use the setup for production purposes and you are developing under Windows or OS/X, installing an XAMPP stack is the way to go. Get the appropriate version for your operating system at:

    But please note that you should under no circumstances use XAMPP to create a production server environment for you.

    Under Linux, use your package manager to download and install the necessary packages. Some distributions, like Ubuntu, package all the necessary applications into one bundle. Just do the following from a terminal window in Ubuntu:

    However you install the necessary elements, please ensure you configure MySQL with a secure root password.

Configure the MySQL Database

  1. Create a MySQL database.

    Log into your database as an administrative user (usually root)

    In this guide we will create a database called "secure_login".

    See how to Create-a-Database-in-Phpmyadmin.

    You can either use the code below or do the same thing in phpMyAdmin/your favourite GUI MySQL client, if you prefer:

    Note: Some hosting services don't allow you to create a database through phpMyAdmin, Learn how to do it in cPanel.
  2. Create a user with only SELECT, UPDATE and INSERT privileges.

    Creating a user with restricted privileges means that if there was ever a breach of security in our script the hacker couldn't delete or drop anything from our database. Using these privileges, you can get by doing pretty much anything you would want to in your application. If you are really paranoid, create a user for each function.

    Of course you will need to be logged into MySQL as a user with sufficient privileges in order to create a user. This user will usually be root.

    These are the details of the user we created:
    • User: "sec_user"
    • Password: "eKcGZr59zAa2BEWU"

    Note: it is a good idea to change the password from the one given above when running on your own server. Make sure, if you do this, that you also change the code below, and your PHP database connection code in the application we are creating.

    Remember it doesn't need to be a password that you can remember so make it as complicated as possible. Here's a random password generator

    Given below is the SQL code for creating the database user and granting it the necessary permissions. Or you can do this in a GUI database client like phpmyadmin if you prefer:

    If you see yourself deleting records from either of the tables in this module, you may want to add DELETE to the list of privileges, or you may prefer to create a different user with just the DELETE privilege, and only on the table from which you want to delete records if you don't want to delete from both. You do not need to grant DELETE privileges at all for anything in this example script.
  3. Create a MySQL table named "members".

    The code below creates a table with four fields (id, username, email, password). We use the BINARY datatype to store the password because it will be encrypted using BCrypt, which has an output length of 60 characters. To store it more efficiently, we store it in the BINARY format:

    IMPORTANT: If you have attempted to use this script with SHA512 hashing and had problems with logging in, you need to change the PASSWORD field to CHAR(128) as the original BINARY(60) cropped out 68 crucial characters at the end of the hashed password, this causes the password to mismatch when attempting to login.

    As we've said before, you can do this in whatever type of client you prefer.
  4. Create a table to store login attempts.

    We will use this table to store login attempts for a user. This is one way in which we will make brute force attacks more difficult:

  5. Create a test row in table "members".

    It will be important to be able to test your login script, so below is the script to create a user with known details:
    • Username: test_user
    • Email:
    • Password: 6ZaxN2Vzm9NUJT2y

    The code you need in order to be able to log in as this user is:

Create Database Connection Page

  1. Create a global configurations page

    Create a folder called "includes" in the root directory of the application and then create a new PHP file in that directory. Call it psl-config.php. In a production environment you'll probably want to locate this file and all your other include files, outside of the web server's document root. If you do that, and we strongly suggest that you do, you will need to alter your include or require statements as necessary, so that the application can find the include files.

    Locating your include files outside of the web server's document root means that your file cannot be located using a URL. So, if someone mistakenly dropped the 'php' extension, say, or messed up the file permissions the file still could not be displayed as text in a browser window.

    The file contains global configuration variables. Things like whether anyone can register, whether or not it's a secure (HTTPS) connection, and other stuff as well as the database details could also go here...

  2. Create the database connection page

    This is the PHP code that we will use to connect to our mySQL database. Create a new PHP file called db_connect.php in the application's includes directory and add the code below. You can then include the file onto any page you wish to connect to the database.

Create the PHP Functions

These functions will do all the processing of the login script. Add all of the functions to a page called functions.php in the includes directory of the application.

  1. Securely start a PHP session.
    PHP sessions are known not to be secure, therefore it is important not just to put "session_start();" at the top of every page on which you want to use PHP sessions. We are going to create a function called "sec_session_start()", this will start a PHP session in a secure way. You should call this function at the top of any page in which you wish to access a PHP session variable. If you are really concerned about security and the privacy of your cookies, have a look at this article: Create-a-Secure-Session-Managment-System-in-Php-and-Mysql.

    This function makes your login script a whole lot more secure. It stops crackers accessing the session id cookie through JavaScript (for example in an XSS attack). Also the "session_regenerate_id()" function, which regenerates the session id on every page reload, helps prevent session hijacking. Note: If you are using HTTPS in your login application set the "$secure" variable to true. In a production environment it is essential that you use HTTPS.

    Create a new file called functions.php in your application's includes directory and add the following code to it:
  2. Create the Login Function.
    This function will check the email and password against the database. Using the password_verify function rather than comparing the strings helps to prevent timing attacks. It will return true if there is a match. Add this function to your functions.php file:

  3. The Brute Force Function.
    Brute force attacks are when a hacker tries thousands of different passwords on an account, either randomly generated passwords or from a dictionary. In our script if a user account has more than five failed logins their account is locked.

    Brute force attacks are hard to prevent. A few ways we can prevent them are using a CAPTCHA test, locking user accounts and adding a delay on failed logins, so the user cannot login for another thirty seconds.

    We strongly recommend using a CAPTCHA. As yet we have not implemented this functionality in the example code, but hope to do so in the near future, using SecureImage, since it does not require registration. You may prefer something better known such as reCAPTCHA from Google.

    Whichever system you decide on, we suggest you only display the CAPTCHA image after two failed login attempts so as to avoid inconveniencing the user unnecessarily.

    When faced with the problem of brute force attacks, most developers simply block the IP address after a certain amount of failed logins. But there are many tools to automate the process of making attacks like these; and these tools can go through a series of proxies and even change the IP on each request. Blocking all these IP addresses could mean you're blocking legitimate users as well. In our code we'll log failed attempts and lock the user's account after five failed login attempts. This should trigger the sending of an email to the user with a reset link, but we have not implemented this in our code. Here is the code for the checkbrute() function at the time of writing. Add it to your functions.php code:

  4. Check logged in status.
    We do this by checking the "user_id" and the "login_string" SESSION variables. The "login_string" SESSION variable has the user's browser information hashed together with the password. To check if they are equal, we use the hash_equals function to prevent timing attacks. We use the browser information because it is very unlikely that the user will change their browser mid-session. Doing this helps prevent session hijacking. Add this function to your functions.php file in the includes folder of your application:

  5. Sanitize URL from PHP_SELF
    This next function sanitizes the output from the PHP_SELF server variable. It is a modificaton of a function of the same name used by the WordPress Content Management System:

    The trouble with using the server variable unfiltered is that it can be used in a cross site scripting attack. Most references will simply tell you to filter it using htmlentities(), however even this appears not to be sufficient hence the belt and braces approach in this function.

    Others suggest leaving the action attribute of the form blank, or set to a null string. Doing this, though, leaves the form open to an iframe clickjacking attack.

Create Processing Pages

  1. Create the login processing page (process_login.php)

    Create a file to process logins, called process_login.php in the application's includes directory. It goes in this directory because it contains no HTML markup.

    We will use the mysqli_* set of PHP functions as this is one of the most up-to-date mySQL extensions.

  2. Create a logout script.

    Your logout script must start the session, destroy it and then redirect to somewhere else. Note: it might be a good idea to add CSRF protection here in case someone sends a link hidden in this page somehow. For more information about CSRF you could visit Coding Horror.

    The current code for logging out the user, which you should add to a file called logout.php in the application's includes directory, is:

  3. Registration Page.

    The registration code is included in two new files, called register.php in the application's root directory and in the includes directory. It does the following things:
    • Obtains and validates the username the user wishes to adopt
    • Obtains and validates the user's email address
    • Obtains and validates the password the user wants to use
    • Hashes the password and passes it back to the register.php page (i.e. it posts to itself)

    Most of the validation is done in JavaScript, client side. This is because the user has no motivation to circumvent these checks. Why would a user want to create an account that would be less secure than otherwise? We will discuss the JavaScript in the next section.

    TIP: $error_msg can be changed into an array instead of simply making it one long string of errors. This is as simple as setting $error_msg = array(); at the top of the file. Then replacing every $error_msg .= to $error_msg[] =. It would also be recommended to remove the html from the $error_msg so all of the errors are in plain text inside of the array. If you want to be able to use the array on the page which you are posting to you can set a posting variable to equal the array like this: $_POST['error_msg'] = serialize($error_msg);, the serialize turns the array into a single string so the post is able to use it. To use this post on the page after registering, simply do: $error_variable = unserialize($_POST['error_msg']);, of course you should always use an if(isset($_POST['error_msg'])) {$error_variable = unserialize($_POST['error_msg']);} as this checks if the variable is actually set.

    For now, just create the register.php file and include the following code in it:

    The file in the includes directory should contain the following code:

    If there is no POST data passed into the form, the registration form is displayed. The form's submit button calls the JavaScript function regformhash(). This function does the necessary validation checks and submits the form when all is well. The JavaScript functions are discussed in the next section.

    If the POST data exists, some server side checks are done to sanitise and validate it. NOTE that these checks are not complete at the time of writing. Some of the issues are mentioned in the comments in the file. At present, we just check that the email address is in the correct format, that the hashed password is the correct length and that the user is not trying to register an email that has already been registered.

    If everything checks out, the new user is registered by writing a new record into the members table.

Create Javascript Files

  1. Create sha512.js file

    This file is an implementation in JavaScript of the hashing algorithm sha512. We will use the hashing function so our passwords don't get sent in plain text.

    The file can be downloaded from

    (It is also saved in the github repository)

    Store your copy of this file in a directory called "js", off the root directory of the application.

  2. Create forms.js file
    This file, which you should create in the js directory of the application, will handle the hashing of the passwords for the login (formhash()) and registration (regformhash()) forms:

    In both cases, the JavaScript hashes the password and passes it in the POST data by creating and populating a hidden field.

Create HTML Pages

  1. Create the login form (index.php).

    This is an HTML form with two text fields, named "email" and "password". The form's submit button calls the JavaScript function formhash(), which will generate a hash of the password, and send "email" and "p" (the hashed password) to the server. You should create this file in the application's root directory.

    When logging in, it is best to use something that is not public, for this guide we are using the email as the login id, the username can then be used to identify the user. If the email is not displayed on any pages within the wider application, it adds another unknown for anyone trying to crack the account.

    Note: even though we have encrypted the password so it is not sent in plain text, it is essential that you use the HTTPS protocol (TLS/SSL) when sending passwords in a production system. It cannot be stressed enough that simply hashing the password is not enough. A man-in-the-middle attack could be mounted to read the hash being sent and use it to log in.

  2. Create the register_success.php page

    Create a new PHP web page called register_success.php, in the root directory of the application. This is the page to which the user is redirected after successfully registering. Of course you can make this page anything you like or redirect to another page entirely (or even not at all). It's up to you. The page should be located in the root directory of the application. The current register_success.php page that we have written looks like this:

  3. Create the error page

    Create a new HTML page in the root directory of the application. Call it error.php This is the page to which users will be directed if an error occurs during the login or registration process, or when trying to establish a secure session. The code given below simply provides a bare bones error page. You will probably need something a bit more sophisticated. However, please note that the input into the page must be properly filtered to guard against XSS attacks. The example page code is:

Protecting Pages

  1. Page Protection Script.

    One of the most common problems with authentication systems is the developer forgetting to check if the user is logged in. It is very important you use the code below on every protected page to check that the user is logged in. Make sure you use this function to check if the user is logged in.

    As an example of what you should do, we have included a sample protected page. Create a file called protected_page.php in the root directory of the application. The file should contain something like the following:

    Our application redirects to this page after a successful login. Your own implementation does not have to do this, of course.


  • With very few changes these example scripts can be modified to work with other SQL systems such as SQLite or Install PostgreSQL Using the Source Code.
  • If you're wanting to use a different hashing algorithm rather than sha512, try Whirlpool. Avoid using Gost, sha1 (Unless thoroughly salted and in multiple iterations), and as already stated, md5. Encourage your users to create strong, unique passwords with both uppercase and lowercase letters, numbers, and symbols. Consider having your users create a separate login name from their username for added security.
  • Stay away from the md5() function in login scripts, the md5 hashing algorithm is now considered insecure.
  • Use HTML and CSS to format the login form and output pages to your liking.


  • The use of a CAPTCHA on the login page is highly recommended to make brute force and DoS attacks more difficult. We recommend that the CAPTCHA appear on the form after two failed login attempts. This is not yet implemented in the example code.
  • The Anti Brute Force of this script, that locks a user account, can be misused very easily. We strongly recommend that you use an anti-brute force technique such as a CAPTCHA.
  • The login page and the Registration page must use HTTPS. The scripts in this article do not force you to do this and, indeed, you may find it easier not to during development. But you should not use these scripts in a production environment unless you are using HTTPS.
  • Nothing is 100% secure. Remember to stay in tune with the latest security news to keep improving the security of your scripts.
  • You may get a better solution than this by using a framework such as Zend 2, Symfony or CakePHP. All of these frameworks have arrangements for secure sessions and modules to assist with the login process. You may also find you write better applications if you use a framework.
  • Centralized sign in solutions exist and are known as Single Sign-On, or SSO. Depending on the need, these may offer superior alternatives to framework sign in solutions since a single login is able to span multiple disparate software applications which may reside on multiple domains. Examples of popular SSO solutions are Barebones SSO, Jasig CAS, and JOSSO.
  • Make sure that the user cannot see your PHP script, which may occur due to an incorrect server setup. There is a possibility of the users gathering information about your database names and passwords if your PHP code is visible. Ideally any scripts that are included in other scripts or pages should be located in a directory outside of the server's file system and referenced using a relative path e.g. include '../../includes/'.

Related Articles

Sources and Citations