In this tutorial, I'll be teaching you how you can create your very own secure PHP login system. A login form is what your website's visitors can use to log in to your website to access restricted content, such as a profile page. We will leverage MySQL to retrieve account data from the database. Show
The includes additional features and a download link to the source code. In addition, it includes the complete tutorial source code. Contents1. Getting StartedThere are a few steps we need to take before we create our secure login system. We need to set up our web server environment and ensure we have the required extensions enabled. 1.1. Requirements
1.2. What You Will Learn in this Tutorial
1.3. File Structure & SetupWe can now start our web server and create the files and directories we're going to use for our login system.
File Structure\-- phplogin Each file will consist of the following:
2. Creating the Login Form DesignWe will now create a form that our users can use to enter their details and submit them for processing. We will be using HTML and CSS for this part of the tutorial as PHP will not be necessary on this page. Edit the index.html file with your favorite code editor and add the following code: HTML
If we navigate to the index page in our web browser, it will look like the following: http://localhost/phplogin/index.html Pretty basic right? Let's edit our style.css file and implement code that will improve the appearance of the form. Add the following code to the style.css file: CSS
We need to include our stylesheet in our index.html file and therefore we must add the following code to the head section: HTML
And now if we refresh the index.html page in our web browser, our login form will look more appealing: http://localhost/phplogin/index.html That looks much better! Let's narrow down the form elements, so we can get a better understanding of what's going on.
3. Creating the Database and setting-up TablesFor this part, you will need to access your MySQL database, either using phpMyAdmin or your preferred MySQL database management application. Follow the below instructions if you're using phpMyAdmin.
You can use your own database name, but for this tutorial, we'll use phplogin. What we need now is an accounts table as this will store all the accounts (usernames, passwords, emails, etc) that are registered with the system. Click the database on the left side panel (phplogin) and execute the following SQL statement: SQL
On phpMyAdmin this should look like: http://localhost/phpmyadmin/ The above SQL statement code will create the accounts table with the columns id, username, password, and email. The SQL statement will insert a test account with the username: test, and the password: test. The test account will be used for testing purposes to ensure our login system is functioning correctly. 4. Authenticating Users with PHPNow that we have our database set up, we can go ahead and start coding with PHP. We're going to start with the authentication file, which will process and validate the form data that we'll send from our index.html file. Edit the authenticate.php file and add the following: PHP
Initially, the code will start the session as this enables us to preserve account details on the server and will be used later on to remember logged-in users. Without sessions, we can't associate the client with the server. Connecting to the database is essential. Without it, how can we retrieve and store information related to our users? Therefore, we must make sure to update the variables to reflect our MySQL database credentials. Add below: PHP
The above code will make sure the form data exists, whereas if the user tries to access the file without submitting the form, it will output a simple error. Add below: PHP
The above code will prepare the SQL statement that will select the id and password columns from the accounts table. In addition, it will bind the username to the SQL statement, execute it, and then store the result. Tip Leveraging prepared statements correctly will secure your SQL queries and therefore prevent SQL injection. After the following line:
Add: PHP
First, we need to check if the query has returned any results. If the username doesn't exist in the database then there would be no results. If the username exists, we can bind the results to both the $id and $password variables. Subsequently, we proceed to verify the password with the password_verify function. Only passwords that were created with the password_hash function will work. If you don't want to use any password encryption method, you can simply replace the following code: PHP
With: PHP 0However, I don't recommend removing the hashing functions because if somehow your database becomes exposed, all the passwords stored in the accounts table will also be exposed. In addition, the user will have a sense of privacy knowing their password is encrypted. Upon successful authentication from the user, session variables will be initialized and preserved until they're destroyed by either logging out or the session expiring. These session variables are stored on the server and are associated with a session ID stored in the user's browser. We'll use these variables to determine whether the user is logged in or not and to associate the session variables with our retrieved MySQL database results. Did you know?The session_regenerate_id() function will help prevent session hijacking as it regenerates the user's session ID that is stored on the server and as a cookie in the browser. The user cannot change the session variables in their browser, and therefore you don't need to be concerned about such a matter. The only variable they can change is the encrypted session ID, which is used to associate the user with the server sessions. Now, we can test the login system and make sure the authentication works correctly. Navigate to http://localhost/phplogin/index.html in your browser. Type in a random username and password, and click the login button. It should output an error that should look like the following: http://localhost/phplogin/authenticate.php Don't worry, it's not broken! If we navigate back to our login form and enter test for both the username and password fields, the authentication page will look like the following: http://localhost/phplogin/authenticate.php If you receive an error, make sure to double-check your code to make sure you haven't missed anything or check if the test account exists in your database. 5. Creating the Home PageThe home page will be the first page our users see when they've logged in. The only way they can access this page is if they're logged in, whereas if they aren't, they will be redirected back to the login page. Edit the home.php file and add the following code: PHP 1Basically, the above code will check if the user is logged in. If they are not, they will be redirected to the login page. Remember the $_SESSION['loggedin'] variable we defined in the authenticate.php file? This is what we can use to determine whether users are logged in or not. After, we can add some HTML to our home page. Below the closing tag, add the following code: PHP 2The above code is the template for our home page. On this page, the user will encounter a welcome message along with their name being displayed. We need to add CSS for the home page. Add the following code to style.css file: PHP 3Now that we have our home page set up, we can redirect our users from the authenticate.php file to our home page, edit authenticate.php and replace the following line of code: PHP 4With: PHP 5If you log in with the test account, you should see something like this: http://localhost/phplogin/home.php This is a pretty basic home page. You can customize it to how you want now that you understand how it works. 6. Creating the Profile PageThe profile page will display the account information for the logged-in user. Edit the profile.php file and add the following code: PHP 6The above code retrieves additional account information from the database, as before with the home page, we didn't need to connect to the database because we retrieved the data stored in sessions. We're going to populate all the account information for the user and therefore we must retrieve the password and email columns from the database. We don't need to retrieve the username or id columns because we've them stored in session variables that were declared in the authenticate.php file. After the closing tag, add the following code: PHP 7A simple layout that will populate account information. If you navigate to the profile.php file, it will look like the following: http://localhost/phplogin/profile.php Remember, the passwords are encrypted, so you cannot see the decrypted password unless you create a new session variable and store the password in the authenticate.php file. 7. Creating the Logout ScriptCreating the logout script is straightforward. All you need to do is destroy the sessions that were declared in the authenticate.php file. Edit the logout.php file and add the following code: PHP 8Initialize sessions, destroy them, and redirect the user to the login page. We use sessions to determine whether the user is logged in or not, so by removing them, the user will not be logged in. ConclusionYou should now have a basic understanding of how a login system works with PHP and MySQL. You're free to use the source code and incorporate it into your own projects. The next step is to create a registration system that will enable visitors to register. Don't forget to follow us and share the article as it will help us create future tutorials and update existing content with new features. Next tutorial in this series: Secure Registration System with PHP and MySQL If you would like to support us, consider purchasing the advanced secure login & registration system below as it will greatly help us create more tutorials and keep our website up and running. The advanced package includes improved code and more features. Advanced$20.00 view more detailsSource Code Database SQL File Secure Login & Registration System Home, Profile & Edit Profile Pages Account Activation Feature Remember Me Feature AJAX Integration PDO, MVC OOP & Basic Versions Admin Panel Add-on: Forgot Password Add-on: Brute Force Protection Add-on: CSRF Protection Add-on: Two-factor Authentication Add-on: Native Captcha Add-on: reCAPTCHA v3 Add-on: Google OAuth Add-on: Facebook OAuth Responsive Design (mobile-friendly) SCSS File Commented Code Free Updates & Support (minor issues) User Guide Extra: Tutorial Source Code PayPalDownload CryptoDownload Sale Bundle (Save 53%)$119.00 255.00 view more detailsSecure Login & Registration System Shopping Cart System CRUD Application Ticketing System Gallery System Event Calendar System Poll and Voting System Commenting System Review System Contact Form Live Support Chat System Newsletter & Mailing System Access to future scripts PayPalDownload CryptoDownload About AuthorDavid AdamsEnthusiastic website developer, I've been designing and developing web applications for over 10 years, I enjoy the creativity I put into my projects and enjoy what others bring to the awesome web. My goal is to help newcomers learn the ways of the web. How to secure a PHP database connection?User has to create a password and use it for login to the website. But it is very important to secure the password of the user. password_hash() function provides the facility to securely store the password of the user to the database.
How do I secure my database connection?Procedure. Identify the user IDs that you want to associate with the database connection, or create a user ID with a password, following the appropriate instructions for your operating system and database.. Define the user IDs and passwords that the integration node can use to access a particular data source.. How to secure database credentials in PHP?I've thought of the following options:. Just leave config. ... . Create a PHP file outside of the web root, something like passwords. ... . Set the database password in an environment variable in the PHP-FPM configuration file (env[DB_PASSWD] = MyPassword). ... . Set the database password in an environment variable defined in the .. Which method is secure for securing data in PHP?Use SSL Certificates For HTTPS
HTTPs provides a secured and encrypted accessing channel for untrusted sites. You must include HTTPS by installing SSL certificate into your website. It also strengthens your web applications against XSS attacks and prevents the hackers to read transported data using codes.
|