Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

PHP · Send a plain email with mail()Intermediate
function clean_header(string $v): string
{
    return trim(preg_replace('/[\r\n]+/', ' ', $v));
}

$to      = 'you@example.com';
$subject = clean_header('New message from ' . $_POST['name']);
$body    = "Name: " . $_POST['name'] . "\nEmail: " . $_POST['email'] . "\n\n" . $_POST['message'];
$headers = [
    'From'         => 'website@example.com',                 // your own address, not the visitor's
    'Reply-To'     => clean_header($_POST['email']),
    'Content-Type' => 'text/plain; charset=UTF-8',
];

mail($to, $subject, $body, $headers);   // array headers need PHP 7.2 or newer

Strip line breaks from anything that goes into a header, otherwise attackers can inject extra headers (header injection). On servers like WampServer, mail() us…

PHP · Send basic security headersIntermediate
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
header("Content-Security-Policy: default-src 'self'; img-src 'self' data:; frame-ancestors 'self'");

// Only on HTTPS sites. Tells browsers to always use HTTPS for a year.
if (!empty($_SERVER['HTTPS'])) {
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}

A few headers that close common attack routes. Test your Content-Security-Policy before you enforce it, because it blocks inline scripts.

PHP · Call a JSON API with cURLIntermediate
function api_get(string $url): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_HTTPHEADER     => ['Accept: application/json'],
    ]);
    $body = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);

    if ($body === false)  throw new RuntimeException('Request failed: ' . $err);
    if ($code !== 200)    throw new RuntimeException('API returned HTTP ' . $code);
    return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}

A GET request with a timeout and proper error checks. Always set timeouts so a slow API cannot freeze your page.

PHP · Serve a private file safelyIntermediate
$dir  = '/var/private-files';                       // NOT inside the web root
$name = basename((string)($_GET['file'] ?? ''));    // strips any folder part
$path = $dir . '/' . $name;

// ... check here that the logged-in user is allowed to get this file ...

if ($name === '' || !is_file($path)) { http_response_code(404); exit('Not found'); }

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($name) . '"');
header('Content-Length: ' . filesize($path));
header('X-Content-Type-Options: nosniff');
readfile($path);
exit;

Keep private files outside the web root and send them through PHP after checking who is asking. basename() blocks ../ tricks.

PHP · Enums (PHP 8.1)Intermediate
enum Status: string
{
    case Draft     = 'draft';
    case Published = 'published';
    case Archived  = 'archived';

    public function label(): string
    {
        return ucfirst($this->value);
    }

    public function isPublic(): bool
    {
        return $this === self::Published;
    }
}

$s = Status::from('published');          // throws on an unknown value
$t = Status::tryFrom('oops');            // null instead
echo $s->label();                        // Published
var_dump($s->isPublic(), $t);            // true, NULL
echo count(Status::cases());             // 3

An enum is a fixed list of allowed values. It replaces loose strings and magic numbers.

PHP · Read a huge file with a generatorIntermediate
function readLines(string $path): Generator
{
    $fh = fopen($path, 'rb');
    if (!$fh) {
        throw new RuntimeException("Cannot open $path");
    }
    try {
        while (($line = fgets($fh)) !== false) {
            yield rtrim($line, "\r\n");
        }
    } finally {
        fclose($fh);
    }
}

$errors = 0;
foreach (readLines(__DIR__ . '/access.log') as $n => $line) {
    if (str_contains($line, ' 500 ')) {
        $errors++;
    }
}

A generator hands out one line at a time, so memory stays small even for a gigabyte file.

PHP · Unicode-safe strings with mb_*Intermediate
$text = 'پاکستان زندہ باد';

echo strlen($text);                       // bytes (not characters)
echo mb_strlen($text);                    // 16 characters
echo mb_substr($text, 0, 7);              // 'پاکستان'
echo mb_strtoupper('straße');             // 'STRASSE'

function excerpt(string $s, int $max = 20): string
{
    return mb_strlen($s) > $max ? mb_substr($s, 0, $max - 1) . '…' : $s;
}

echo excerpt($text, 8);                  // 'پاکستان…' is 8 characters

strlen() counts bytes. For Urdu, Arabic or emoji use the mb_ functions.

PHP · array_reduce and array_walkIntermediate
$cart = [
    ['name' => 'Pen',    'price' => 1.5, 'qty' => 4],
    ['name' => 'Book',   'price' => 12,  'qty' => 2],
];

$total = array_reduce($cart, fn($sum, $i) => $sum + $i['price'] * $i['qty'], 0);   // 30

array_walk($cart, function (&$item, $key) {
    $item['line'] = $item['price'] * $item['qty'];
});

$grouped = [];
foreach ($cart as $i) {
    $grouped[$i['qty'] > 3 ? 'bulk' : 'single'][] = $i['name'];
}

array_reduce folds a list into one value. array_walk changes items in place.

PHP · Send the right HTTP status codeIntermediate
function fail(int $code, string $message): never
{
    http_response_code($code);
    header('Content-Type: text/plain; charset=utf-8');
    echo $message;
    exit;
}

// 404 page not found
$post = null;
if (!$post) {
    fail(404, 'Page not found');
}
// 403 forbidden, 401 not logged in, 405 wrong method, 429 too many requests, 503 maintenance
header('Retry-After: 3600');          // use with 429 / 503

Search engines and APIs read the status code. Do not return 200 for an error page.

PHP · Send JSON to an API with cURLIntermediate
function postJson(string $url, array $data): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($data, JSON_THROW_ON_ERROR),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Accept: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT        => 15,
    ]);
    $body   = curl_exec($ch);
    $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error  = curl_error($ch);
    curl_close($ch);

    if ($body === false) {
        throw new RuntimeException('Request failed: ' . $error);
    }
    return ['status' => $status, 'data' => json_decode($body, true)];
}

Set a timeout, check the HTTP status and always close or reuse the handle.

PHP · Log errors and show a safe pageIntermediate
ini_set('display_errors', '0');                       // never show errors to visitors
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/logs/php-error.log');

set_error_handler(function (int $no, string $msg, string $file, int $line) {
    throw new ErrorException($msg, 0, $no, $file, $line);
});

set_exception_handler(function (Throwable $e) {
    error_log(get_class($e) . ': ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(500);
    echo 'Something went wrong. Please try again later.';
});

Turn warnings into exceptions, log details privately and show visitors only a plain message.

PHP · Read settings from a .env fileIntermediate
// /home/site/.env  (outside public_html)
//   DB_HOST=localhost
//   DB_NAME=mydb
//   APP_DEBUG=false

$env = parse_ini_file('/home/site/.env', false, INI_SCANNER_TYPED);
if ($env === false) {
    http_response_code(500);
    exit('Config missing');
}

$host  = $env['DB_HOST'] ?? 'localhost';
$debug = (bool)($env['APP_DEBUG'] ?? false);

Keep passwords out of your code. Put them in a file outside the web folder and read it once.

PHP · Convert a time between time zonesIntermediate
$utc = new DateTimeImmutable('2026-11-03 09:00:00', new DateTimeZone('UTC'));

$karachi = $utc->setTimezone(new DateTimeZone('Asia/Karachi'));
echo $karachi->format('Y-m-d H:i T');        // 2026-11-03 14:00 PKT

$ny = $utc->setTimezone(new DateTimeZone('America/New_York'));
echo $ny->format('H:i T');                   // 04:00 EST

Store dates in UTC and convert only when you show them.

PHP · Date difference and adding timeIntermediate
$start = new DateTimeImmutable('2026-01-15');
$end   = new DateTimeImmutable('2026-11-03');

$diff = $start->diff($end);
echo $diff->days;                           // total days: 292
echo $diff->m, ' months ', $diff->d, ' days';

$due  = $start->add(new DateInterval('P30D'));       // +30 days
echo $due->format('Y-m-d');                          // 2026-02-14
echo $start->modify('last day of this month')->format('Y-m-d');   // 2026-01-31

DateTimeImmutable never changes the original, which avoids many bugs.

$line = '2026-11-03 14:30 ERROR Disk full';

if (preg_match('/^(?<date>\d{4}-\d{2}-\d{2}) (?<time>\d{2}:\d{2}) (?<level>[A-Z]+) (?<msg>.+)$/', $line, $m)) {
    echo $m['date'], ' ', $m['level'], ' ', $m['msg'];      // 2026-11-03 ERROR Disk full
}

// find all numbers
preg_match_all('/\d+/', 'a1 b22 c333', $all);                // $all[0] = ['1','22','333']

// replace with a callback
$out = preg_replace_callback('/\d+/', fn($x) => $x[0] * 2, 'a1 b22');   // a2 b44

Named groups give readable results. Always check that preg_match() returned 1.

PHP · Decode JSON and catch bad inputIntermediate
function readJson(string $raw): array
{
    try {
        $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        throw new InvalidArgumentException('Invalid JSON: ' . $e->getMessage());
    }
    if (!is_array($data)) {
        throw new InvalidArgumentException('JSON must be an object or array');
    }
    return $data;
}

$body = readJson(file_get_contents('php://input') ?: '{}');
echo json_encode(['ok' => true, 'items' => count($body)], JSON_THROW_ON_ERROR);

JSON_THROW_ON_ERROR turns silent failures into exceptions you can catch.

PHP · Log out properlyIntermediate
session_start();

$_SESSION = [];
if (ini_get('session.use_cookies')) {
    $p = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
}
session_destroy();

header('Location: /login.php');
exit;

Clear the data, expire the cookie and destroy the session, then send the user somewhere safe.

PHP · Safe LIKE search (escape % and _)Intermediate
function likeEscape(string $text): string
{
    return addcslashes($text, '\\%_');
}

$q  = '50%';
$st = $pdo->prepare('SELECT id, name FROM users WHERE name LIKE ? ORDER BY name LIMIT 20');
$st->execute(['%' . likeEscape($q) . '%']);
$rows = $st->fetchAll();

Prepared statements stop injection, but % and _ typed by the user still act as wildcards. Escape them.

PHP · A safe WHERE ... IN (...) listIntermediate
$ids = [1, 3, 4];                                  // from the user: cast them first
$ids = array_map('intval', $ids);

if ($ids) {
    $marks = implode(',', array_fill(0, count($ids), '?'));
    $st = $pdo->prepare("SELECT id, name FROM users WHERE id IN ($marks)");
    $st->execute($ids);
    $rows = $st->fetchAll();
}

Build one ? per value and pass the array to execute(). Never glue the values into the SQL.

PHP · Update and delete with a row countIntermediate
$st = $pdo->prepare('UPDATE users SET name = ? WHERE id = ?');
$st->execute(['Ali Khan', 1]);
if ($st->rowCount() === 0) {
    echo 'No change (user missing or same name)';
}

$st = $pdo->prepare('DELETE FROM users WHERE id = ?');
$st->execute([2]);
echo $st->rowCount() . ' row(s) deleted';

rowCount() tells you how many rows changed, so you can answer "not found" properly.

PHP · Insert a row and get its new idIntermediate
$st = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
$st->execute([':name' => 'Bilal', ':email' => 'bilal@example.com']);

$newId = (int)$pdo->lastInsertId();
echo "Created user #$newId";

Use a prepared INSERT, then lastInsertId() to read the auto-increment id.

PHP · Autoload classes (PSR-4 style)Intermediate
spl_autoload_register(function (string $class): void {
    $prefix = 'App\\';
    $base   = __DIR__ . '/src/';

    if (strncmp($class, $prefix, strlen($prefix)) !== 0) {
        return;                                   // not our namespace
    }
    $file = $base . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
    if (is_file($file)) {
        require $file;
    }
});

// src/Util/Str.php  contains:  namespace App\Util;  class Str { ... }
echo \App\Util\Str::upper('ok');

Map a namespace to a folder and let PHP load each class file when it is first used.

PHP · Reuse code with a traitIntermediate
trait HasSlug
{
    public function slug(): string
    {
        $s = strtolower(trim(preg_replace('/[^A-Za-z0-9]+/', '-', $this->title), '-'));
        return $s !== '' ? $s : 'item';
    }
}

class Post
{
    use HasSlug;
    public function __construct(public string $title) {}
}

class Page
{
    use HasSlug;
    public function __construct(public string $title) {}
}

echo (new Post('Hello, World!'))->slug();    // hello-world

A trait adds methods to any class without inheritance. Good for small shared helpers.

PHP · Interfaces and abstract classesIntermediate
interface Notifier
{
    public function send(string $to, string $message): bool;
}

abstract class BaseNotifier implements Notifier
{
    protected function clean(string $text): string
    {
        return trim(strip_tags($text));
    }
}

class LogNotifier extends BaseNotifier
{
    public array $sent = [];

    public function send(string $to, string $message): bool
    {
        $this->sent[] = $to . ': ' . $this->clean($message);
        return true;
    }
}

function alert(Notifier $n): void
{
    $n->send('admin', '<b>Disk almost full</b>');
}

$log = new LogNotifier();
alert($log);

An interface is a promise of methods. An abstract class shares code and leaves the rest to the child classes.

class Product
{
    public function __construct(
        public string $name,
        private float $price,
        private int $stock = 0,
    ) {}

    public function price(): float
    {
        return $this->price;
    }

    public function inStock(): bool
    {
        return $this->stock > 0;
    }

    public function withDiscount(int $percent): static
    {
        $copy = clone $this;
        $copy->price = round($this->price * (100 - $percent) / 100, 2);
        return $copy;
    }
}

$p = new Product('Mouse', 20.0, 5);
echo $p->withDiscount(25)->price();    // 15

Constructor promotion (PHP 8) declares and sets the properties in one place. Type everything.

PHP · Export a query to CSVIntermediate
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="users.csv"');

$out = fopen('php://output', 'w');
fputcsv($out, ['ID', 'Name', 'Email']);
foreach ($pdo->query('SELECT id, name, email FROM users') as $row) {
    fputcsv($out, $row);
}
fclose($out);

Stream rows straight to the browser as a CSV download.

PHP · Simple pagination with PDOIntermediate
$perPage = 10;
$page    = max(1, (int)($_GET['page'] ?? 1));
$total   = (int)$pdo->query('SELECT COUNT(*) FROM posts')->fetchColumn();
$pages   = max(1, (int)ceil($total / $perPage));
$page    = min($page, $pages);
$offset  = ($page - 1) * $perPage;

$st = $pdo->prepare("SELECT * FROM posts ORDER BY id DESC LIMIT $perPage OFFSET $offset");
$st->execute();
$rows = $st->fetchAll();

Count the rows, work out the page and fetch only that slice.

PHP · Validate an image uploadIntermediate
$f = $_FILES['photo'] ?? null;
if ($f && $f['error'] === UPLOAD_ERR_OK && $f['size'] <= 5 * 1024 * 1024) {
    $mime = (new finfo(FILEINFO_MIME_TYPE))->file($f['tmp_name']);
    $ext  = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'][$mime] ?? null;
    if ($ext && getimagesize($f['tmp_name'])) {
        $name = bin2hex(random_bytes(8)) . '.' . $ext;
        move_uploaded_file($f['tmp_name'], __DIR__ . '/uploads/' . $name);
    }
}

Check the real file type (not just the extension) and store it under a random name.

PHP · CSRF token for formsIntermediate
// create (once per session)
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}

// in the form
echo '<input type="hidden" name="_csrf" value="' . $_SESSION['csrf'] . '">';

// on submit
if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['_csrf'] ?? '')) {
    http_response_code(403);
    exit('Invalid request.');
}

Create a token per session, put it in every form and check it with hash_equals().

PHP · Secure login with sessionsIntermediate
session_start();

$st = $pdo->prepare('SELECT id, password_hash FROM users WHERE username = ?');
$st->execute([$_POST['username'] ?? '']);
$user = $st->fetch();

if ($user && password_verify($_POST['password'] ?? '', $user['password_hash'])) {
    session_regenerate_id(true);
    $_SESSION['uid'] = $user['id'];
    header('Location: dashboard.php');
    exit;
}
$error = 'Wrong username or password.';

Verify the password hash, then regenerate the session id so old ids cannot be reused.