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.
Short PHP answers, each with the mistake that makes the common version fail.
Requests. Check the request method, not a field, because a browser sends nothing for an unticked checkbox. Redirect a page with three lines and three ways to get it wrong, including a 301 the browser caches.
Images. Convert WebP to JPG or PNG (paint onto white first or transparency turns black), convert PNG and JPG to WebP while keeping the original when the WebP is larger, and check every image on a page from the command line in a deploy check.
Parsing and templates. loadHTML garbles UTF-8 because it assumes Latin-1; the post tests four fixes. Render Twig outside a controller by injecting the Environment.
Search these 7 posts
Everything in PHP Snippets

10/28/2026
PHP loadHTML Garbles UTF-8: Characters Turn Into é
DOMDocument::loadHTML reads text without an encoding hint as Latin-1, so accents and symbols break. Four ways to fix it, with the result of each.

10/08/2026
PHP: Check Every Image on a Page for Broken URLs
A PHP command-line script that lists every img on a page and reports each image's HTTP status. It exits non-zero when any are broken, so it works in a deploy check.

09/27/2026
WebP to JPG in PHP: Paint on White or Get Black Areas
Load with imagecreatefromwebp(), save with imagejpeg() or imagepng(). For JPG, paint onto white first or transparent pixels turn black.

08/23/2025
PNG and JPG to WebP in PHP: Quality 82, Keep the Smaller
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.

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.](/media/cover-php-was-form-posted-card-400x225.webp)
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.

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.