This tutorial is intended to explain how to design and build the foundation of a secure user authentication system using PHP's PDO library with a MySQL database. Each security measure is explained and justified, and many contain references to additional information should you wish to explore the subject in more depth. This article highlights insecure practices commonly found in code written by beginning PHP programmers who are simply unaware of how to write secure code. This tutorial lives at DevShed Forums. Be sure to visit for up-to-date information and discussions.
This tutorial is aimed at programmers with a basic knowledge of PHP and MySQL. It assumes that you already have:
To use this login system you will need to create a database using the provided SQL file. You will need to upload the remaining files to your web server. Please read through the comments in each file and edit as necessary per the instructions.
In common.php:
An example of a protected page can be found in private.php. Protecting a page is as easy as including the common.php file and checking whether or not a user is logged in.
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
A working demo of this code can be seen at http://www.basicsecurelogin.com.
Personal support requests should be made at the Dev Shed Forums.
This code is made freely available. Anyone and everyone is welcome to contribute. If you would like to get involved, please review the guidelines:
The code is available under the MIT license.
A special thanks to the contributing members at Dev Shed Forums who freely give of their time and expertise so that others may learn. If you find this code useful, please stop by the forums and say thanks.