Hey there, tech wizards and coding enthusiasts! Max from A1WebsitePro here, ready to dive deeper into our web development journey. In our last tutorial, we built a signup script using Ajax, jQuery, Bootstrap, and PHP. Now, let's level up by adding login and logout functionalities to our application.
Starting Up
First things first, let's get our LAMP server running:
Windows/Mac: Fire up your XAMPP server. Just look for XAMPP in the start windows and fire it up.
Linux Folks: Open your terminal, navigate to the root directory with ls, and start your LAMP server with sudo /opt/lampp/lampp start. Don't forget your password!
cd /
sudo /opt/lampp/lampp start
To verify:
Open a browser, type localhost, and you should see the XAMPP or LAMP welcome page. Navigate to phpMyAdmin where we've got two users, John Smith and Ali Smith, ready but not yet able to log in.
Streamlining the Code
I hate messy code as much as I hate ads popping up when I'm trying to focus. Let’s tidy up:
- Create login.php: We're going to clean up our signup.php by externalizing scripts and styles, creating a more modular and maintainable codebase.
<?php require_once 'header.php'; ?> <!-- Login form here --> <?php require_once 'footer.php'; ?>
- JavaScript Optimization: Move the inline JS to an external file signup.js or login.js for cleaner pages.
Login Logic
Our login script needs to:
- Validate Input: Ensure both email and password are provided and the email is in the correct format.
if(empty($_POST['email_login']) || empty($_POST['password_login'])) { echo "Please fill in both email and password."; exit; } if(!filter_var($_POST['email_login'], FILTER_VALIDATE_EMAIL)) { echo "Invalid email format."; exit; }
- Database Query: Fetch user details if the email exists.
$stmt = $conn->prepare("SELECT id, password FROM users WHERE email = ?"); $stmt->bind_param("s", $_POST['email_login']); $stmt->execute();
- Password Verification: Use
password_verify()
to check if the provided password matches the hashed one in the database. - Session Management: If credentials match, start a session and redirect.
Logout Functionality
- Create logout.php:
session_start(); session_destroy(); <h1>You have been logged out. Come back soon!</h1>
Add A Logout Link in the Menu
<a href="logout.php">Log Out</a>
Wrap Up
Stay tuned for more web wizardry from A1WebsitePro. Until next time, keep coding clean and your coffee strong! Get scripts here if you are not a subscriber.
By now, you should have a working login and logout system. Remember, it's all about making your site user-friendly and secure. Next up, we'll delve into session variables, user customization, and more to make your site not just functional but personal!