Code Snippets

Short, copy-pasteable answers to problems that come back around, each one checked against the current version rather than the one it was written for.

Filter these 36 posts

Everything in this section

  • Diagram: HttpClient through authInterceptorFn, which adds an Authorization header before the request reaches the server, with the 401 response looping back to the interceptor.

    09/02/2026

    An Angular auth interceptor, the functional way

    Attach a token to every outgoing request and handle a 401 in one place, using the functional HttpInterceptorFn rather than the class-based interceptor most search results still show.

  • Diagram: a ten-line for-loop on the left replaced by a two-line Collectors.groupingBy stream on the right, with the record it groups into shown beneath.

    09/02/2026

    Grouping and summarizing a list in modern Java

    Collectors.groupingBy with a downstream collector replaces most of the loop-and-map code people still write - plus records, which remove the class that loop needed.

  • Diagram: readFileSync crashing on a 2GB file, compared against createInterface reading the same file in constant kilobytes.

    09/02/2026

    Reading a huge file line by line in Node, without loading it

    readFileSync on a 2GB log is how a Node process dies. Streaming it line by line uses a constant few kilobytes instead, and is barely more code.

  • 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.

  • Diagram: three retry attempts at growing intervals, beside a note that 429 and 5xx are retried while 4xx is not.

    09/02/2026

    Retrying an HTTP request in Python, properly

    A retry with exponential backoff and jitter that only retries what is worth retrying - and does not hammer a service that is already struggling.

  • Diagram: a role hierarchy showing ROLE_ADMIN above ROLE_USER, beside three IS_AUTHENTICATED variants marked with which ones a plain visitor passes.

    09/02/2026

    is_granted in Twig: roles and IS_AUTHENTICATED

    is_granted takes more than roles, and picking the wrong one gives you a check that quietly passes when it should not. What each attribute tests, why role hierarchy makes ROLE_USER true for your admins, and where the check belongs.

  • Diagram: a crossed-out FOSUserBundle block opening into four replacement components -- Security, MakerBundle, ResetPasswordBundle and VerifyEmailBundle.

    09/02/2026

    Leaving FOSUserBundle: what replaces each piece

    The bundle is maintained only enough for existing projects to migrate off it. Every piece it provided now has a replacement in Symfony itself or in two small bundles - and the migration is mostly deletion.

  • Diagram: individually labeled form_row fields inside a form_start/form_end frame, with a form_rest chip carrying the CSRF token at the bottom.

    09/02/2026

    Rendering a Symfony form field by field in Twig

    One call renders the whole form and gives you no say in the markup. Splitting it up is four functions, and the one that matters most is form_rest - the safety net that stops a forgotten field from silently disappearing.

  • Diagram: autoescape on, punctured by |raw, with three contexts named where that filter is the wrong answer -- attribute, URL, inline JS and CSS.

    09/02/2026

    Twig autoescaping and the raw filter

    Autoescaping makes Twig safe by default and makes |raw the fastest way to undo that. The catch is that HTML escaping is only correct in HTML - inside a script tag or an unquoted attribute, the default is the wrong answer.

  • Diagram: a loop firing fifty queries at a database, compared against the same loop firing one query after addSelect().

    09/02/2026

    The N+1 you wrote in a Twig loop, and its fix

    The query looks fine and the template looks fine. Together they issue one query per row, because a lazy association is loaded the moment a template touches it - and templates touch things the controller never did.

  • Diagram: five ng CLI commands worth memorizing, with one flag flagged as having moved in Angular 19.

    08/23/2025

    Angular 19 CLI commands worth memorizing

    Here are the top Angular 19 CLI commands every developer should know since you will likely use them every day. Click here to get your free Angular 19 Cheat Sheet & Study Guide!

  • 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.

  • Two teachers standing in the rain entering car pickup numbers on cell phones

    08/17/2025

    Why is school car-line pickup still typed in by hand?

    Here’s a practical application that can help schools with parent pickup and reduce unpleasant tasks and time burdening school staff.

  • 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 group of unchecked checkboxes gated by a some() check before the submit button is allowed to fire.

    12/27/2015

    Require at least one checkbox, in plain JavaScript

    Check so at least one checkbox on your form is checked before it’s allowed to submit:

  • 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: addError() called from a controller landing on a specific field's inline error and on the form's own top-level error banner.

    06/11/2015

    Adding a form error from a controller in Symfony

    Some checks cannot live in a constraint because they need something the form does not know about. FormError attaches the message to a field, or to the form itself, so it renders where the user is looking.

  • Diagram: a browser's cookie flowing into a Symfony Request object and out into a Twig template reading app.request.cookies.get('name').

    04/02/2015

    How to show or access cookie values in Symfony Twig views

    Strange how obscure it is to find a clear example of how to just access or show the value of a cookie in Twig, so here it is!

  • Diagram: the Request object at the center with arrows out to a Controller, a Service and a Twig template, and one arrow in from routing where the locale is set.

    01/01/2015

    Reading the current locale in Symfony

    The locale lives on the Request, not in a global. How to reach it from a controller, from a service that has no request, and from a template - and where it is set before any of that.

  • Diagram: setFirstResult and setMaxResults windowing a slice of a row stack, beside a fetch-joined collection case routed to Paginator instead.

    01/01/2015

    Limiting a Doctrine query with setMaxResults

    Here is an example of a simple DQL query in a custom repository method meant to return a single array result. The following will return the latest result in case there are multiple contact records that match the…

  • Diagram: three grouped rows of records, two intact and one struck through entirely because a single row inside it matched the excluded value.

    12/21/2014

    MySQL: exclude a whole group when any row matches

    Querying databases get a little tricky when you have a stack of records associated with another table, perhaps a master table of accounts, and you’re trying to filter out values that would exclude the results from…

  • Diagram: MM and YYYY select fields feeding a DataTransformer that outputs a DateTime, beside a struck-through DateType with a hidden day control.

    11/19/2014

    A card expiry month/year field in Symfony

    The old answer was to render DateType's day dropdown and hide it with CSS. That works until somebody uses a screen reader. Two choice fields and a small transformer do the job honestly.

  • Diagram: the DISALLOW_FILE_EDIT constant cutting the line from a stolen admin password to the in-admin PHP file editor.

    11/16/2014

    Disable the WordPress theme and plugin file editor

    To tighten security of your WordPress site, you can disable users’ ability to edit your theme and plug-in files. After all, isn’t that what your web development team should be doing?

  • Diagram: an array of IDs feeding into a Doctrine query that filters with WHERE ... IN, bound through setParameter.

    09/04/2014

    Doctrine's equivalent of SQL IN()

    MySQL’s “IN” query filter is very useful. Basically, if you have a list of record ID numbers, you can query them all neatly like so:

  • Diagram: a DataTransformer throwing an exception into a field that shows a generic message, beside an alternative field showing custom text built from the invalid value.

    08/20/2014

    invalid_message: what a failed transformer shows

    A transformer that cannot convert what was typed throws, and Symfony turns that into a message the user reads. Left alone it says nothing useful; invalid_message is where you replace it.

  • Diagram: the WordPress admin frame with Tasks, Milestones and Calendar panels added inside it, replacing a separate project-management app.

    08/06/2014

    CollabPress: project management inside WordPress

    Some people are so enamored with these shiny new project management tools that load so nicely on our smart phones that they forget it should be a transparent part of the project and not a task and part of the process of…

  • Symfony Dynamic Form Collections and data-prototype in Twig

    06/24/2014

    Symfony collection prototype: formatting it in Twig

    Let’s say you are creating a form in Symfony that has some dynamic fields that you need to allow the user to add and remove a subset of options and fields from within the form.

  • Diagram: one contact-form plugin branching into three separate forms, Sales, Support and Careers, each routed to its own address.

    03/16/2014

    Need multiple contact forms on your WordPress website?

    There are plenty of contact form plug-ins for WordPress. I’ve used a few that I thought would be good but turned out to be barely functional, clunky, and/or buggy.

  • 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.

  • Diagram: a shortcode with category and limit arguments feeding a list of post cards, each carrying a thumbnail and an excerpt.

    03/08/2014

    A WordPress shortcode that lists posts or pages

    In WordPress, you can do a lot with shortcodes, the problem is, some work fine then one day they just break. It’s best to stick with ones that work reliably, even when you upgrade.

  • Diagram illustrating why floated elements of unequal heights snag and leave layout gaps

    02/26/2014

    Make elements match heights across a row

    There are some new CSS tricks coming out that will allow for this to be done natively, but until then, here’s a way to make sure that all elements in a page, say gallery thumbnails or excerpts from posts, all display…

  • Insert PHP Code in WordPress via Shortcode

    02/26/2014

    Including a PHP file from a WordPress shortcode, safely

    The 2014 version of this shortcode takes a file path out of the post and includes it, which is a local file inclusion hole with extra steps. The fix is small: let the code decide which files are includable, not the person writing the post.

  • Diagram: the three WordPress debug constants and the combination that is safe to leave on for a live site.

    02/26/2014

    Turn on WordPress Debugging

    When you’re in development mode, it’s useful to get errors in scripts as they occur. Just place this line anywhere in your functions.php file for your active child theme and you will start seeing debug feedback complete…

  • Diagram: the comment_form() call in comments.php replaced by one with an empty comment_notes_after, trimming the trailing markup it used to add.

    02/25/2014

    Remove the markup WordPress adds after a comment form

    Find the line in your child theme’s “comment.php” file where it calls on the function comment_form() and replace that line with this:

  • Diagram: Doctrine's flush() taking two paths, a silent commit or a thrown exception that has to be caught by type.

    11/19/2013

    Knowing whether a Doctrine insert or update worked

    Doctrine has no return value to check after flush() - it signals failure by throwing. Wrapping it is the right instinct, but the version of this snippet that has been circulating since 2013 catches nothing at all.