Learn PHP Programming

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

PHP File Handling

PHP provides powerful functions for reading, writing, and managing files. From simple one-liners to stream-based operations, you can handle everything from config files to large CSV datasets.

fopen / fread / fwrite / fclose — Stream-Based I/O

file_streams.php
<?php
// Writing to a file with fopen
$handle = fopen('log.txt', 'a'); // 'a' = append, 'w' = overwrite, 'r' = read
if ($handle === false) {
    die('Cannot open file for writing');
}

fwrite($handle, date('Y-m-d H:i:s') . " - User logged in\n");
fwrite($handle, date('Y-m-d H:i:s') . " - Page viewed\n");
fclose($handle); // Always close the handle!

// Reading a file line by line (memory efficient for large files)
$handle = fopen('log.txt', 'r');
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo htmlspecialchars(trim($line)) . "<br>";
    }
    fclose($handle);
}

// Reading a specific number of bytes
$handle = fopen('data.bin', 'r');
$header = fread($handle, 1024); // Read first 1KB
fclose($handle);
?>

Stream-based functions give you fine-grained control: read specific byte ranges, process files line by line without loading everything into memory, and handle binary data. Always use fclose() to release the file handle.

file_get_contents / file_put_contents — Simple Approach

file_simple.php
<?php
// Write entire content at once
$data = [
    'name' => 'My App',
    'version' => '2.1.0',
    'debug' => false
];
file_put_contents('config.json', json_encode($data, JSON_PRETTY_PRINT));

// Read entire file into a string
$config = json_decode(file_get_contents('config.json'), true);
echo $config['name']; // My App

// Append to a file (FILE_APPEND flag)
file_put_contents('visitors.log', date('c') . " - New visit\n", FILE_APPEND);

// Read file into an array (one element per line)
$lines = file('visitors.log', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
echo "Total visits: " . count($lines);

// Lock file during write to prevent race conditions
file_put_contents('counter.txt', $count, LOCK_EX);
?>

These convenience functions handle opening, reading/writing, and closing in one call. They're perfect for small files. Use LOCK_EX flag when multiple processes might write simultaneously. For files larger than a few MB, prefer stream-based functions.

Reading CSV Files

csv_reader.php
<?php
// Reading a CSV file line by line
$handle = fopen('products.csv', 'r');
if ($handle === false) {
    die('Cannot open CSV file');
}

// Read header row
$headers = fgetcsv($handle);
// ['id', 'name', 'price', 'stock']

// Read data rows
$products = [];
while (($row = fgetcsv($handle)) !== false) {
    // Combine headers with values for named keys
    $products[] = array_combine($headers, $row);
}
fclose($handle);

// Now you can work with structured data
foreach ($products as $product) {
    echo "{$product['name']}: \${$product['price']}\n";
}

// Writing CSV data
$handle = fopen('export.csv', 'w');
fputcsv($handle, ['Name', 'Email', 'Joined']); // Header
fputcsv($handle, ['Alice', 'alice@example.com', '2024-01-15']);
fputcsv($handle, ['Bob', 'bob@example.com', '2024-03-22']);
fclose($handle);
?>

fgetcsv() handles quoted fields, escaped delimiters, and multi-line values automatically. Combine with array_combine() to get associative arrays. This approach processes large CSV files without loading them entirely into memory.

Checking File Existence and Permissions

file_checks.php
<?php
$filepath = __DIR__ . '/data/config.json';

// Check existence and type
if (!file_exists($filepath)) {
    die("File not found: $filepath");
}

if (!is_file($filepath)) {
    die("Path is not a regular file");
}

// Check permissions before operations
if (!is_readable($filepath)) {
    die("File is not readable - check permissions");
}

if (!is_writable($filepath)) {
    die("File is not writable - check permissions");
}

// Get file information
echo "Size: " . filesize($filepath) . " bytes\n";
echo "Modified: " . date('Y-m-d H:i:s', filemtime($filepath)) . "\n";
echo "Type: " . mime_content_type($filepath) . "\n";

// Create directory if it doesn't exist
$uploadDir = __DIR__ . '/uploads';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true); // recursive creation
}

// Safe file deletion
if (file_exists($filepath) && is_writable($filepath)) {
    unlink($filepath);
}
?>

Always verify file existence and permissions before operations. Use __DIR__ for reliable absolute paths. The mkdir() with the recursive flag creates nested directories in one call.

Key Takeaways

  • Always close file handles with fclose() — open handles can cause resource leaks and file locking issues.
  • Check for errors on every file operation; fopen() returns false on failure.
  • Use absolute paths with __DIR__ to avoid issues with changing working directories.
  • Use LOCK_EX when writing files that may be accessed by concurrent processes.
  • Verify permissions with is_readable()/is_writable() before operations to provide clear error messages.
Best Practice

For production applications, wrap file operations in try-catch blocks and use SplFileObject for an object-oriented interface. Never construct file paths from user input without sanitization — use basename() and validate against a whitelist of allowed directories to prevent directory traversal attacks.

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.