Users Table
For this tutorial, we need to setup our Users table first. Create the table by running this SQL query in your PHPMyAdmin page:
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(25) NOT NULL, `password` char(32) NOT NULL, PRIMARY KEY (`id`) );
We have our Users table ready, let’s add a dummy record there. Insert a new record by following the instructions here.
Login Page
What we need now is our login page. Create a new page called login and save it in your pages folder as login.php and add the following codes:
<form method="post"> <input type="hidden" name="action" value="login_user"> <input type="text" name="username" placeholder="Username"><br> <input type="password" name="password"><br> <input type="submit" value="Login Now"> </form>
In the code snippet above, you’ll notice that we have a hidden field with a name action and the value is login_user. This means that when we click “Login Now”, the action “login_user.php” in the actions folder gets executed.
Login Action
After the user submits the form, we need to make sure that we catch all the information they sent. Since we used the post method in our form, we will use $_POST to handle the login details and check if the user exists. Add the following codes in your login_user.php:
<?php if( isset( $_POST[ 'username' ] ) && isset( $_POST[ 'password' ] ) ) { $username = $_POST[ 'username' ]; $password = md5( $_POST[ 'password' ] ); $result = $DB->query( "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1" ); if( $result && $result->num_rows > 0 ) { $user = $result->fetch_object(); $_SESSION[ 'userid' ] = $user->id; $_SESSION[ 'username' ] = $user->username; echo "Welcome back " . $_SESSION[ 'username' ] . "!"; } } else { echo "Please fill all the fields."; } ?>
Explanation:
Line #2: Checks if the username and password field have been filled-in.
Line #4: We encrypt the password to match our encrypted password in the database.
Line #5: We check in the database if the username and password exists in our Users table.
Line #6: We check if the query returns a record.
Line #8 and #9: We use $_SESSION to remember the user details. You can read more about sessions here. Please take note that sessions are automatically started in Lorem-Framework.
Now we have a basic Login feature in our site, you can further improve it and make more experiment to fully understand.