PHP File & Date Utilities

Key Takeaway: Practice PHP programming with 84+ practical code examples covering syntax, arrays, strings, functions, OOP, JSON, and file handling — all with expected terminal outputs.

Audience & Use Case: Designed for web developers, backend engineers, Laravel developers, computer science students, and interview candidates mastering modern PHP.

Last updated: September 2026 84 Verified Examples

Quick Start & How to Use

  1. Select a PHP program topic from the sidebar menu (or mobile dropdown).
  2. Examine the clear PHP code syntax and corresponding terminal output.
  3. Copy the code directly or run it live in our Online PHP Compiler.
  4. Experiment with arrays, functions, and OOP classes to solidify your server-side programming skills.

Who is this for: Web developers, Laravel learners, API engineers, and CS students.

Related Tools:PHP Compiler · PHP Official Manual · JavaScript Examples · Python Examples

How to delete text from file using preg_replace() function in PHP?

Run Online

Reads a file, matches pattern using regex, replaces with empty string, and saves.

Program (PHP)
<?php

$content = "DEBUG [2026-09-01]: Test message.\nINFO: User logged in.\nDEBUG [2026-09-01]: Another trace.";

$cleanedContent = preg_replace('/DEBUG.*?\n/s', '', $content);

echo "Cleaned File Content:\n$cleanedContent\n";
?>
Expected Output
Cleaned File Content:
INFO: User logged in.
DEBUG [2026-09-01]: Another trace.

PHP Date and Time Formatting

Run Online

Formats current date and time using date() and strtotime().

Program (PHP)
<?php

date_default_timezone_set('UTC');

echo "Current Date: " . date('Y-m-d H:i:s') . "\n";
echo "Formatted: " . date('F j, Y, g:i a') . "\n";
echo "Tomorrow: " . date('Y-m-d', strtotime('+1 day')) . "\n";
?>
Expected Output
Current Date: 2026-09-01 22:45:00
Formatted: September 1, 2026, 10:45 pm
Tomorrow: 2026-09-02

PHP File Reading and Writing Example

Run Online

Demonstrates file_put_contents and file_get_contents for quick file handling.

Program (PHP)
<?php

$filename = "sample.txt";
$content = "Hello, PHP File System!\nWritten on: " . date('Y-m-d');

file_put_contents($filename, $content);

$readContent = file_get_contents($filename);
echo "File Content:\n" . $readContent . "\n";
?>
Expected Output
File Content:
Hello, PHP File System!
Written on: 2026-09-01

How to parse a CSV File in PHP?

Run Online

Parses CSV data lines using str_getcsv() or fgetcsv().

Program (PHP)
<?php

$csvData = "Name,Role,City\nAlice,Developer,New York\nBob,Designer,London\nCharlie,Manager,Tokyo";

$lines = explode("\n", trim($csvData));
$header = str_getcsv(array_shift($lines));
$rows = [];

foreach ($lines as $line) {
    $rows[] = array_combine($header, str_getcsv($line));
}

print_r($rows);
?>
Expected Output
Array
(
    [0] => Array
        (
            [Name] => Alice
            [Role] => Developer
            [City] => New York
        )

    [1] => Array
        (
            [Name] => Bob
            [Role] => Designer
            [City] => London
        )

    [2] => Array
        (
            [Name] => Charlie
            [Role] => Manager
            [City] => Tokyo
        )

)

How to upload images in MySQL using PHP PDO?

Run Online

Demonstrates image file validation, directory upload, and PDO path storage.

Program (PHP)
<?php

function processImageUpload($fileName, $fileTmp, $fileSize) {
    $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
    $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    
    if (!in_array($ext, $allowedTypes)) {
        return "Invalid file type.";
    }
    if ($fileSize > 2 * 1024 * 1024) {
        return "File size exceeds limit (2MB).";
    }
    
    $newFilename = uniqid('img_') . '.' . $ext;
    $uploadDir = 'uploads/' . $newFilename;
    
    return "Success! Stored path for PDO insertion: " . $uploadDir;
}

echo processImageUpload("profile.png", "/tmp/php123", 500000) . "\n";
?>
Expected Output
Success! Stored path for PDO insertion: uploads/img_66d4f9e12a.png

How to get a File Extension in PHP?

Run Online

Extracts file extensions using pathinfo() and PATHINFO_EXTENSION.

Program (PHP)
<?php

$filename = "document.report.v2.pdf";

$extension = pathinfo($filename, PATHINFO_EXTENSION);

echo "File: $filename\n";
echo "Extension: $extension\n";
?>
Expected Output
File: document.report.v2.pdf
Extension: pdf

PHP Core Concepts & Feature Breakdown

DomainCore ConceptsPrimary Use CaseOfficial Docs
Variables & Types$var, string, int, boolVariables, string concatenation, type declarationsPHP Types
Arrays & DataIndexed arrays, Associative ['key' => 'val']Key-value mappings, list iteration with foreachPHP Arrays
Functionsfunction name(type $param): returnTypeModular code, default arguments, return value typingPHP Functions
OOP Constructsclass, extends, public/protectedEncapsulation, constructors, inheritance, web frameworksPHP OOP

Keep Practicing

Use the online PHP compiler to test snippet modifications, test array manipulation logic, and build custom functions for backend applications.

Frequently Asked Questions

You can run all snippets instantly in your browser using our Online PHP Compiler without setting up Apache, Nginx, or local PHP runtimes.

Yes. All programs utilize modern PHP standard syntax, typed properties/arguments, short array syntax [], and standard OOP paradigms compatible with PHP 7.4 through PHP 8.x and frameworks such as Laravel and Symfony.

Absolutely. These examples cover essential backend concepts frequently requested during technical evaluations: string operations, prime checks, Fibonacci algorithms, associative array iteration, JSON parsing, and object-oriented inheritance.

Learn PHP by Practicing Examples

PHP powers over 75% of the active web today. Practicing short, clear programs is the most efficient path to mastering PHP backend development. Each snippet focuses on a fundamental building block — from basic variable output and control structures to complex associative arrays, JSON serialization, and object-oriented design.

Beginner Foundations

Learn echo syntax, variable assignment, type coercion, and simple arithmetic operations.

Arrays & Logic

Master key-value arrays, foreach loops, function type hints, and string/math helpers.

OOP & Files

Explore classes, inheritance, visibility, JSON APIs, and file read/write operations.