Learning guide
Secure login with sessions, password_verify, and MySQL users table. The walkthrough below uses PHP Login Page (MySQL) as the worked example.
Work in a folder named php-login-mysql on localhost. Break the code on purpose once; fixing it teaches more than a clean import.
Read a section, predict what should happen, then run it. Logs and the browser network tab are part of the lesson.
If local setup is new to you, block an hour once for Apache/MySQL or Live Server, then reuse that stack for other guides.
Start from login.php when you open the reference tree. The optional package at the bottom matches this article.
Concepts you should understand
Authentication labs cover identity, sessions, and password hashing. Upload labs cover validation, storage layout, and metadata. AJAX labs cover HTTP verbs, JSON contracts, and separating view from API. Map each file in the reference section to one of these ideas.
Optional local lab setup
PHP labs assume a local MySQL schema imported from the teaching database.sql file. These steps describe a learning environment, not commercial software installation.
- Create a folder under your local web root named
php-login-mysqlfor this exercise. - Start Apache and MySQL services on your machine (only needed for PHP/MySQL lessons).
- Import the bundled
database.sqlthrough phpMyAdmin to create practice tables. - Adjust
config.phpcredentials to match your local database user. - Open
http://localhost/php-login-mysql/login.phpand step through each screen while reading the source. - Credentials for sandbox testing, if any, are documented only inside the private
README.txtshipped with the practice archive—not on this public page.
Guided walkthrough
Begin by using the feature as a learner: submit empty forms, invalid emails, and edge cases.
Watch how the UI responds, then locate the PHP or JavaScript responsible for that message.
Trace variables from $_POST or fetch bodies down to SQL or DOM updates.
Rewrite one branch in your own words—rename fields, add comments, or log values with error_log or console.debug.
If behavior changes unexpectedly, you have found a learning moment about sessions, scope, or async timing.
For topics like PHP Login Page (MySQL), compare your work against the annotated snippets below before peeking at the full reference tree. Spaced repetition (revisit the lesson days later) cements syntax into long-term memory better than a single rushed pass.
Annotated code samples
Each block is meant to be edited, not pasted blindly. Read the note under it, then try one small change.
Guarding pages with server-side sessions
<?php
session_start();
if (empty($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}session_start() resumes the visitor session from the session cookie. If user_id is missing, the user has not authenticated, so PHP sends a redirect instead of private content. Calling exit immediately after header prevents accidental output that would break the redirect.
Sessions identify a visitor across requests using a server-side record and a session cookie. The cookie is only a pointer; authorization logic must still check roles and ownership on every sensitive action. In production, combine sessions with HTTPS, HttpOnly cookies, and CSRF tokens on state-changing forms.
Checking passwords with password_verify()
<?php
if ($user && password_verify($password, $user['password_hash'])) {
$_SESSION['user_id'] = (int) $user['id'];
header('Location: dashboard.php');
}password_verify() compares the typed password against a bcrypt hash stored in MySQL. Unlike MD5 or SHA1, bcrypt is designed for passwords: it is slow, salted, and resistant to rainbow tables. Only after a successful verify should you write the user id into $_SESSION and redirect to an authenticated area.
Why bcrypt beats MD5 for login: MD5 was built for speed and fingerprints, not for secrets. Attackers can compute billions of MD5 guesses per second on consumer hardware, and leaked MD5 databases (rainbow tables) make cracking common passwords trivial. Bcrypt, used by PHP’s password_hash() and password_verify(), is intentionally slow and stores a unique salt inside each hash string. That means identical passwords produce different hashes, and offline cracking costs far more time and money. For coursework, always verify with password_verify instead of comparing raw strings or legacy MD5/SHA1 digests.
Run the happy path first, then try empty fields or bad IDs on purpose.
Querying one user with a prepared statement
<?php
require __DIR__ . '/config.php';
$stmt = db()->prepare('SELECT id, name FROM users WHERE email = ? LIMIT 1');
$stmt->bind_param('s', $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();require loads shared database settings so every script uses one connection helper. The prepared statement uses a ? placeholder so user input is never concatenated into SQL. bind_param attaches the email string safely, and fetch_assoc returns one row as an associative array for login checks.
Prepared statements separate SQL structure from user data, which closes the most common SQL injection holes taught in security courses. Even when you trust your own form today, future features (search boxes, admin filters) often reuse the same query patterns—building them safely from day one prevents expensive refactors.
Compare this block with the previous one: notice what stayed the same and what had to change for this screen.
Security notes for students
Practice code deliberately simplifies reality. Before any production deployment, add HTTPS, rate limiting, logging, and professional review. Never reuse tutorial passwords in public systems. Remove sample accounts and disable verbose errors on live hosts.
Legal: Globaltuts.com is not responsible for security vulnerabilities if practice code is deployed on a live production server without proper sanitization. Read our practice project policy, Privacy Policy, and Disclaimer.