Code Snippets

PHP Snippets

Short answers to problems PHP has had for years, written for the version you are actually running rather than the one in the old blog post.

Search these 6 posts

Everything in PHP Snippets

  • Diagram: fgetcsv reading one row at a time, beside file() hitting the memory limit on the same file.

    09/02/2026

    Reading a huge CSV in PHP without exhausting memory

    file() and str_getcsv on a large export will hit the memory limit. Streaming it with fgetcsv uses a few kilobytes regardless of file size, and handles quoted newlines correctly.

  • Converting PNG and JPG Images to WebP

    08/23/2025

    Convert PNG and JPEG to WebP with a PHP script

    A short GD script that converts a folder to WebP, preserves PNG transparency, and - the part usually missing - keeps the original whenever the WebP comes out larger, which happens more than you would think.

  • Rendering Twig from Symfony Repositories Without DI

    07/04/2019

    Rendering a Twig template outside a controller

    You do not need a controller to render Twig, and you should not pass the container around to get at it. Inject the Environment, and use createTemplate when the template itself comes from the database.

  • Diagram: a passing check on $_SERVER['REQUEST_METHOD'] beside a failing check on isset($_POST['agree']), an unticked checkbox that a browser never sends.

    12/28/2015

    Checking whether a form was posted, in PHP

    Testing for a field is the common way and it is wrong: a browser sends nothing at all for an unticked checkbox, so the form looks unsubmitted. Test the method instead.

  • Diagram: a single apiCall(url, method, data) function branching into a GET and a POST request, both landing on the same JSON response.

    12/26/2015

    A simple cURL wrapper for calling any API

    Since you likely interface with a lot of external APIs, there’s no need to keep rewriting the same tool. Just copy this and use the “apiBaseController” class as you need it.

  • Diagram: three passing requirements for a PHP redirect, an absolute URL, an exit after it and no prior output, above a failing example under a headers-already-sent error.

    03/15/2014

    Redirect a webpage with PHP

    Three lines, and three ways to get it wrong: output before the header, no exit after it, and a 301 the browser then caches forever. Which status you choose matters more than the code does.