Learn PHP Programming
Master PHP programming from basics to advanced concepts with our comprehensive tutorial series. Perfect for beginners and web developers.
PHP Sessions & Cookies
HTTP is stateless — each request is independent. Sessions and cookies solve this by persisting data between requests: sessions store data server-side, cookies store it client-side in the browser.
Sessions — Starting, Setting, and Reading
<?php
// Must be called before ANY output (including whitespace)
session_start();
// Setting session variables
$_SESSION['username'] = 'alice';
$_SESSION['role'] = 'admin';
$_SESSION['login_time'] = time();
// Reading session variables
echo "Hello, " . htmlspecialchars($_SESSION['username']);
echo "Role: " . $_SESSION['role'];
// Check if a session variable exists
if (isset($_SESSION['username'])) {
echo 'User is logged in';
}
// Remove a specific session variable
unset($_SESSION['role']);
// Destroy the entire session
session_unset(); // Clear all session variables
session_destroy(); // Destroy the session file
?>
session_start() either creates a new session or resumes an existing one using the session ID from the cookie. Session data lives on the server (typically in files), so it's safe for sensitive information. Always call it before any HTML output.
Login/Logout Session Flow
<?php
session_start();
// --- LOGIN (login.php) ---
function loginUser(string $username, string $password): bool {
// Fetch user from database (pseudo-code)
$user = getUserByUsername($username);
if ($user && password_verify($password, $user['password_hash'])) {
// Regenerate ID to prevent session fixation
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['logged_in'] = true;
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['last_activity'] = time();
return true;
}
return false;
}
// --- PROTECTED PAGE (dashboard.php) ---
function requireAuth(): void {
if (empty($_SESSION['logged_in'])) {
header('Location: login.php');
exit;
}
// Check session timeout (30 minutes)
if (time() - $_SESSION['last_activity'] > 1800) {
session_unset();
session_destroy();
header('Location: login.php?expired=1');
exit;
}
$_SESSION['last_activity'] = time(); // Refresh timer
}
// --- LOGOUT (logout.php) ---
function logoutUser(): void {
$_SESSION = []; // Clear data
// Delete session cookie
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params['path'], $params['domain'],
$params['secure'], $params['httponly']
);
}
session_destroy();
header('Location: login.php');
exit;
}
?>
A complete auth flow regenerates the session ID on login (prevents fixation), checks for session timeout on each request, and properly destroys both server data and the session cookie on logout.
Cookies — Setting with Secure Flags
<?php
// Modern cookie syntax (PHP 7.3+) with options array
setcookie('preferences', json_encode(['theme' => 'dark', 'lang' => 'en']), [
'expires' => time() + (86400 * 30), // 30 days
'path' => '/', // Available on all pages
'domain' => '', // Current domain only
'secure' => true, // HTTPS only
'httponly' => true, // Not accessible via JavaScript
'samesite' => 'Lax' // CSRF protection
]);
// "Remember me" token (use a separate secure token, NOT the password)
$rememberToken = bin2hex(random_bytes(32));
setcookie('remember_token', $rememberToken, [
'expires' => time() + (86400 * 90), // 90 days
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
// Store hashed token in database for verification
// Delete a cookie
setcookie('preferences', '', [
'expires' => time() - 3600,
'path' => '/'
]);
?>
httponly prevents JavaScript access (mitigates XSS theft). secure ensures cookies only travel over HTTPS. samesite adds CSRF protection. Always set all three flags for security-sensitive cookies.
Reading Cookies with $_COOKIE
<?php
// Cookies are available on the NEXT request after being set
// Always validate and provide defaults
// Reading with null coalescing
$theme = $_COOKIE['theme'] ?? 'light';
// Reading JSON cookie safely
$prefs = [];
if (isset($_COOKIE['preferences'])) {
$decoded = json_decode($_COOKIE['preferences'], true);
if (json_last_error() === JSON_ERROR_NONE) {
$prefs = $decoded;
}
}
// Check remember-me cookie for auto-login
if (!isset($_SESSION['logged_in']) && isset($_COOKIE['remember_token'])) {
$token = $_COOKIE['remember_token'];
// Look up token in database, verify it's valid and not expired
$user = findUserByRememberToken(hash('sha256', $token));
if ($user) {
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['logged_in'] = true;
}
}
?>
Never trust cookie values — they can be modified by users. Always validate, sanitize, and provide defaults. For remember-me tokens, store a hashed version in the database and compare using hash_equals().
Key Takeaways
- Call
session_regenerate_id(true)after login to prevent session fixation attacks. - Always set
httponlyandsecureflags on cookies to prevent XSS theft and man-in-the-middle attacks. - Implement session timeouts — expire idle sessions after 15-30 minutes for sensitive applications.
- Store minimal data in sessions — just user ID and role; fetch details from the database as needed.
- Never store sensitive data in cookies — they're client-side and can be read or modified by users.
Best Practice
Configure session settings in php.ini or at runtime: set session.cookie_httponly = 1, session.cookie_secure = 1, session.use_strict_mode = 1, and session.cookie_samesite = Lax. This hardens all sessions by default without relying on developers remembering to set flags manually on each cookie.
Frequently Asked Questions
PHP Programming Tutorial — Learn PHP from Scratch
PHP (PHP: Hypertext Preprocessor) is the most widely-used server-side scripting language for web development. It powers over 77% of all websites with known server-side languages, including WordPress, Facebook, Wikipedia, and Slack. This comprehensive tutorial series takes you from complete beginner to confident PHP developer with hands-on examples you can run and modify.
Each topic in this tutorial includes multiple runnable code examples with line-by-line explanations, best practice tips, and navigation to the next logical concept. Whether you are learning PHP for the first time or refreshing your knowledge of a specific feature, every page is designed to give you practical, immediately-usable code.
What You Will Learn in This PHP Tutorial
- Basics: Syntax, variables, constants, data types, operators
- Strings & Arrays: Manipulation, searching, sorting, multidimensional arrays
- Control Flow: if/else, switch, for, while, foreach loops
- Functions: Parameters, return values, scope, anonymous functions
- Superglobals: $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER
- Forms: Handling user input, validation, file uploads
- File Handling: Reading, writing, and manipulating files
- Sessions & Cookies: User state management across requests
- OOP: Classes, objects, inheritance, interfaces, traits
- Error Handling: try/catch, custom exceptions, error reporting
- Database: MySQL connection, CRUD operations, prepared statements
- Security: SQL injection prevention, XSS, CSRF, password hashing
Why Learn PHP in 2026?
Despite the rise of Node.js and Python, PHP remains the backbone of web development for compelling reasons:
- Job market demand: Thousands of PHP developer positions available globally. WordPress alone powers 43% of all websites and requires PHP.
- Framework ecosystem: Laravel (the most popular web framework), Symfony, CodeIgniter, and Slim provide professional-grade tooling.
- Low barrier to entry: Shared hosting supports PHP out of the box. No complex server configuration needed to get started.
- PHP 8.x improvements: JIT compiler, named arguments, match expressions, union types, fibers — modern PHP is fast and expressive.
- CMS dominance: WordPress, Drupal, Joomla, Magento, WooCommerce all run on PHP. Knowing PHP gives you access to this entire ecosystem.
- Freelancing opportunities: PHP projects dominate freelance platforms. Many small businesses need WordPress customisation and PHP-based solutions.
PHP Version History (Key Milestones)
| Version | Year | Key Features |
|---|---|---|
| PHP 5.0 | 2004 | Full OOP support, PDO, improved XML |
| PHP 7.0 | 2015 | 2x speed improvement, scalar type declarations, null coalesce operator |
| PHP 7.4 | 2019 | Arrow functions, typed properties, preloading |
| PHP 8.0 | 2020 | JIT compiler, named arguments, match expression, union types, attributes |
| PHP 8.1 | 2021 | Enums, fibers, readonly properties, intersection types |
| PHP 8.2 | 2022 | Readonly classes, DNF types, deprecate dynamic properties |
| PHP 8.3 | 2023 | Typed class constants, json_validate(), #[Override] attribute |
How to Get Started with PHP
- Install a local environment — download XAMPP (Windows/Mac/Linux) or Laravel Valet (Mac). This gives you Apache, PHP, and MySQL in one package.
- Create your first file — make a file called
index.phpin your web root and add:<?php echo "Hello, World!"; ?> - Run it in browser — start Apache and visit
http://localhost/index.phpto see output. - Follow this tutorial series — work through each topic in order, running every example on your local setup.
- Build a project — after completing basics through OOP, build a simple CRUD app (todo list, blog, or contact form) to solidify your knowledge.
Frequently Asked Questions
Basic HTML knowledge is helpful since PHP is often embedded in HTML pages. You do not need to be an HTML expert — understanding tags, forms, and page structure is enough to start.
Yes. PHP and React serve different roles. React is frontend; PHP is backend. Laravel (PHP) is often used as the API backend for React frontends. WordPress (PHP) powers 43% of the web. The job market for PHP developers remains strong.
Laravel is the most popular and has the best documentation, ecosystem, and community. Learn core PHP first (this tutorial), then move to Laravel. Other options: Symfony (enterprise), CodeIgniter (lightweight), Slim (microframework for APIs).
Yes. Use our free online code editors to write and execute PHP code directly in your browser. This is perfect for learning and testing snippets without local setup.
Who Is This Tutorial For?
Complete beginners who want to learn their first programming language for web development. Self-taught developers filling gaps in their PHP knowledge. Students preparing for web development courses or exams. WordPress developers who want to understand the PHP underneath themes and plugins. Backend developers from other languages (Python, Node.js) learning PHP for a new project. Anyone preparing for PHP developer job interviews.
Master PHP Programming with Our Comprehensive Tutorial
Our PHP programming tutorial is designed to take you from a complete beginner to an advanced PHP developer. Whether you're looking to build dynamic websites, create web applications, or start a career in web development, this tutorial series provides everything you need to succeed.
What You'll Learn
- PHP fundamentals and syntax
- Variables, data types, and operators
- Control structures and loops
- Functions and arrays
- Object-oriented programming
- Database integration with MySQL
- Web forms and user input handling
- Security best practices
PHP remains one of the most popular programming languages for web development, powering millions of websites worldwide. Our tutorial includes practical examples, real-world projects, and best practices to ensure you learn not just the syntax, but how to write clean, efficient, and secure PHP code.