Learn PHP Programming

Master PHP programming from basics to advanced concepts with our comprehensive tutorial series. Perfect for beginners and web developers.

PHP Security

Protect your PHP applications from common vulnerabilities including SQL injection, XSS, CSRF, and weak password storage. Follow these security practices to build robust, production-ready code.

1. SQL Injection Prevention

SQL injection occurs when user input is directly concatenated into queries. Always use prepared statements.

sql_injection.php
<?php
// VULNERABLE - Never do this!
$email = $_GET['email'];
$sql = "SELECT * FROM users WHERE email = '$email'";  // Attacker can inject SQL
$result = $pdo->query($sql);  // Dangerous!

// SAFE - Use prepared statements with named placeholders
$email = $_GET['email'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// SAFE - Positional placeholders for multiple parameters
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > ? AND status = ?");
$stmt->execute([$_GET['min_age'], 'active']);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// SAFE - Using bindParam for explicit type control
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = :id");
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
?>

2. XSS (Cross-Site Scripting) Prevention

XSS attacks inject malicious scripts into pages viewed by other users. Always escape output.

xss_prevention.php
<?php
// VULNERABLE - Directly outputting user input
$name = $_GET['name'];
echo "<h1>Welcome, $name</h1>";  // Attacker can inject: <script>alert('XSS')</script>

// SAFE - Escape all output with htmlspecialchars
$name = $_GET['name'];
$safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
echo "<h1>Welcome, $safeName</h1>";

// Create a reusable escape helper function
function e(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

// Usage in HTML context
echo '<p>User: ' . e($user['name']) . '</p>';
echo '<input type="text" value="' . e($user['bio']) . '">';

// For JavaScript context, use json_encode
echo '<script>var userData = ' . json_encode($user, JSON_HEX_TAG) . ';</script>';
?>

3. Password Hashing

Never store plain-text passwords. Use PHP's built-in password_hash() and password_verify() functions.

password_security.php
<?php
// Registration - Hash the password before storing
function registerUser(PDO $pdo, string $email, string $password): bool {
    // Validate password strength
    if (strlen($password) < 8) {
        throw new InvalidArgumentException('Password must be at least 8 characters.');
    }

    // Hash with bcrypt (default algorithm, auto-generates salt)
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    $stmt = $pdo->prepare("INSERT INTO users (email, password) VALUES (:email, :password)");
    return $stmt->execute([
        ':email'    => $email,
        ':password' => $hashedPassword
    ]);
}

// Login - Verify the password against the stored hash
function loginUser(PDO $pdo, string $email, string $password): ?array {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
    $stmt->execute([':email' => $email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || !password_verify($password, $user['password'])) {
        return null;  // Invalid credentials (don't reveal which one is wrong)
    }

    // Rehash if algorithm/cost has changed
    if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
        $newHash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE users SET password = :password WHERE id = :id");
        $stmt->execute([':password' => $newHash, ':id' => $user['id']]);
    }

    return $user;
}
?>

4. CSRF Protection

Cross-Site Request Forgery tricks users into submitting malicious requests. Use tokens to verify form submissions.

csrf_protection.php
<?php
session_start();

// Generate a CSRF token
function generateCsrfToken(): string {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Validate the CSRF token
function validateCsrfToken(string $token): bool {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// In your HTML form
$token = generateCsrfToken();
echo '<form method="POST" action="/update-profile">';
echo '<input type="hidden" name="csrf_token" value="' . e($token) . '">';
echo '<input type="text" name="name">';
echo '<button type="submit">Update</button>';
echo '</form>';

// In your form handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        http_response_code(403);
        die('Invalid CSRF token. Request rejected.');
    }
    // Process the form safely...
    unset($_SESSION['csrf_token']);  // Regenerate for next request
}
?>

5. Input Validation with filter_var

Validate and sanitize all user input using PHP's filter functions before processing.

input_validation.php
<?php
// Validate email
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false) {
    die('Invalid email address.');
}

// Validate integer with range
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 1, 'max_range' => 120]
]);
if ($age === false) {
    die('Invalid age value.');
}

// Sanitize a string (remove tags, encode special chars)
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_SPECIAL_CHARS);

// Validate URL
$website = filter_var($_POST['website'] ?? '', FILTER_VALIDATE_URL);
if ($website === false) {
    die('Invalid URL.');
}

// Validate IP address
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);

// Combined validation function
function validateUserInput(array $data): array {
    $errors = [];
    if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email address.';
    }
    if (empty($data['name']) || strlen($data['name']) > 100) {
        $errors[] = 'Name is required and must be under 100 characters.';
    }
    if (!filter_var($data['age'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 18]])) {
        $errors[] = 'You must be at least 18 years old.';
    }
    return $errors;
}
?>

Key Takeaways

  • Prevent SQL injection by always using prepared statements with bound parameters — never concatenate user input into queries.
  • Prevent XSS by escaping all output with htmlspecialchars() and using json_encode() for JavaScript contexts.
  • Hash passwords with password_hash() using PASSWORD_DEFAULT and verify with password_verify().
  • Implement CSRF tokens on all state-changing forms using cryptographically secure random tokens.
  • Validate all input with filter_var() and filter_input() before processing any user-submitted data.
Best Practice Alert

Review the OWASP Top 10 regularly to stay informed about the most critical web application security risks. Implement defense in depth: combine input validation, output escaping, parameterized queries, CSRF protection, and secure session management. No single measure is sufficient on its own.

Keywords: XSS, SQL injection, password_hash, OWASP, CSRF, input validation, filter_var, htmlspecialchars, prepared statements

Frequently Asked Questions

PHP is a server-side scripting language designed for web development. It powers over 75% of websites on the internet, including Facebook, Wikipedia, and WordPress. Learning PHP opens doors to web development careers and freelance opportunities.

No, PHP is beginner-friendly with simple syntax. However, basic understanding of HTML and CSS will be helpful since PHP is often used to create dynamic web pages.

With PHP, you can build dynamic websites, web applications, content management systems, e-commerce platforms, APIs, and much more. Popular platforms like WordPress, Drupal, and Magento are built with PHP.

Basic PHP can be learned in 2-4 weeks with consistent practice. To become proficient and learn advanced concepts like frameworks and best practices, it typically takes 3-6 months of regular learning and practice.

You need a web server (Apache/Nginx), PHP interpreter, and a database (MySQL). The easiest way is to install XAMPP, WAMP, or MAMP which includes all these tools. You'll also need a text editor like VS Code or PhpStorm.

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)

VersionYearKey Features
PHP 5.02004Full OOP support, PDO, improved XML
PHP 7.020152x speed improvement, scalar type declarations, null coalesce operator
PHP 7.42019Arrow functions, typed properties, preloading
PHP 8.02020JIT compiler, named arguments, match expression, union types, attributes
PHP 8.12021Enums, fibers, readonly properties, intersection types
PHP 8.22022Readonly classes, DNF types, deprecate dynamic properties
PHP 8.32023Typed class constants, json_validate(), #[Override] attribute

How to Get Started with PHP

  1. Install a local environment — download XAMPP (Windows/Mac/Linux) or Laravel Valet (Mac). This gives you Apache, PHP, and MySQL in one package.
  2. Create your first file — make a file called index.php in your web root and add: <?php echo "Hello, World!"; ?>
  3. Run it in browser — start Apache and visit http://localhost/index.php to see output.
  4. Follow this tutorial series — work through each topic in order, running every example on your local setup.
  5. 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

Do I need to know HTML before learning PHP?

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.

Is PHP still relevant with frameworks like React/Next.js?

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.

Which PHP framework should I learn first?

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).

Can I run PHP code online without installing anything?

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.