Blog
-
Creating a Weather Based Email Image Generator
Some years ago I built out a tool to generate dynamic images for email campaigns based on a variety of different parameters, like random selections from an Instagram gallery, animated gifs marking a countdown, and product images based on the weather in a given area. The latter of those is very simple to do with free APIs. Contents Concept Creating the App Outline …
-
Form Validation Essentials
Form validation is an essential process for maintaining data integrity, enhancing the user experience, and ensuring security of your website or service. The importance of form validation cannot be overstated. It plays a vital role in protecting both the user and the system from potential harm. For users, it ensures that their input is acknowledged and processed correctly, reducing frustration and improving…
-
Building a Web-Based Character Picker
I've spent the last couple of years learning German, and one of the things I've come to rely on greatly are tools to help select the correct characters that aren't immediately available on my standard QWERTY keyboard. Even beyond foreign languages, there are countless times when I've needed to use something that wasn't easily typed, so these tools have become invaluable. Contents Not All…
-
Testing Exception Not Thrown With PHPUnit
Testing exceptions in PHPUnit is fairly easy, and you can be as specific as you need with testing the details of the exceptions being thrown. But what if you need to test that an exception wasn't thrown? The Exception Problem There are many clean code advocates who will tell you that testing for exceptions not being thrown is a sign that your code is doing something wrong, and that the code…
-
Testing Multiple Calls To One Method With PHPUnit
Typically if you find yourself in a situation where a method needs to make repeated calls to a single other method with varying values, you will look for a way to implement this into some form of batch call. This simplifies it into a single call that takes a single object, list, or array. Sometimes though this isn't possible, perhaps because the method being called belongs to an external class that…
-
Teaching Children with the Speech API
My eldest son is in the process of learning the alphabet, so I thought I could put my skills to use by helping him learn using two of the things he loves most: mobile devices and Mario! Like all 3 year olds, he loves technology, and we use it as an incentive for many things, from general good behviour to potty training. I've been incredibly impressed with how well he's taken to using a Switch and a…
-
PHP EnumType: an Alternative to SplEnum
When it comes to data types, PHP doesn't come with much out of the box. That's where SPL comes in, a collection of more complex object types and interfaces. One of the types that it comes with is SplEnum which is part of the SplTypes and is not installed by default. On Linux and Unix systems, this isn't a major problem, as there are available packages to install it easily, but if you're running…
-
Using preg_replace_callback() - Find Replace on Steroids
The preg_replace_callback() function in PHP is one of the many regular expression functions available in the language, and can be incredibly powerful as they offer far more versatility when replacing matched text. I recently wanted to use it to implement a very basic templating class. This function goes beyond the preg_replace() function which is just a standard regular expression find/replace.…
-
Formatting File Sizes For Other Languages
Whenever you're dealing with files on the web, you'll likely come to a point where you need to display the size of that file, whether it's to show the size of an attachment on an email, or on a list of downloads for your own Linux distro. Now it might suit your purposes just fine to leave this in English, but if you're trying to venture out into new worldwide markets, you may want to format the…
-
PHP 7.4 Upcoming Features
The last few years has seen PHP undergo an incredible amount of work to improve the language. The latest couple of proposals for the 7.4 release contains a major feature that many have wanted in PHP for years: typed properties on object instances. Typed Properties This is the big one we've all been waiting for. As a developer who works across many languages, being able to type the properties…
-
Creating a Streaming Proxy with PHP
When using cURL the most typical code examples will have you fetch a whole remote response in one go by putting it into a variable. This is fine for small requests, like a web page, but when you scale up, you will run into issues with memory consumption, timeouts, and a poor user experience. A Simple Proxy Extending the Functionality Stream the Response The Result Imagine the scenario…
-
CatImgPHP - Preview Images on the Command Line with PHP
I was reading an article recently about the catimg tool used to preview images on the command line. I saw this as a fun way to keep my PHP skills sharp. The Inspiration I installed the catimg tool locally to test it out and see what kind of output it produced. It's included in most Linux distributions, and is available on MacOS via Homebrew, but Windows users will need to build it from source…
-
PHP 7.3 Upcoming Features
Although PHP 7.3 doesn't have a released spec yet, it's a fairly good bet looking at the list of approved RFC documents at what we can expect in the next release of PHP 7. Exceptions with JSON Errors Allow a Trailing Comma in Function Calls …
-
Single Div CSS Mona Lisa
In the world of CSS, there is little as fun and challenging as the single <div> challenge. It's a creative idea that's been taken to some impressive lengths by Lynn Fisher of the 'A Single Div' website. The technique has been picked up by many front-end developers, who have created some amazing works with it, like Sasha's Mike Wazowski, and the wonderfully festive Christmas tree by Ari…
-
PHPUnit - Testing Core PHP Methods
A lot of my focus recently has been outside of PHP so I'm trying to spend some of my personal time working on a personal project. My recent child (code-wise, not my actual child which would go to explain why my time is so lacking the past year) is imogen which is a system built to generate images for email as the email client requests them. My Christmas reading of Clean Code and The Clean Coder game…
-
Imogen – An Open Source Image Generator For Emails
A couple of years ago I was working closely with some email developers to develop a system that could generate images on the fly. This was born of the need for emails to have content that could change after the moment it was sent, and be fresh at the point a recipient opened it. The end result of this system was a rudimentary system written in PHP that could generate such images, and it was used…
-
Speed Testing the SPL Iterators for Fetching Files
In the world of PHP some techniques never really go away, despite there being better alternatives added to the core functionality. One of these areas is file iteration, particularly recursively through directories and their contents. It's fairly typical to see some code use a recursive function to: Scan a directory Loop through the scanned list Add entry to a list Check if an entry is a…
-
A Formatting Class For PHP Command Line Scripts
Just over a year ago when I moved into my flat, I found myself at a loose end in that time between moving in and the Internet connection being set up. Having exhausted all my films, and played my fill of Red Alert, I was in desperate need for something to do. This PHP script is the culmination of that free time; a command line script that can turn basic HTML strings into something that can be displayed…
-
Creating your own classes that use the PSR-4 autoloader
The PSR-4 standard has been around for quite a while now, building on and adding to the PSR-0 standard, allowing PHP to autoload classes using a cleaner and better organised file tree. One thing I did notice is that not all the documentation on the autoloader is as clear as it could be with regards to how you would actually use it for your own new classes. The first thing would be to get a PSR-4…
-
Code-Free Views
I've recently been embarking on a mission to completely eliminate PHP code from my view files, here is why. What are Views? Often when you're building a website or application, if you build from scratch you end up doing a lot of the same kinds of things, like turning requests into specific pages, handling form validation, caching, etc. A long while ago (in the 70's according to http://c2.com/cgi/wiki?ModelViewControllerHistory)…
-
CodeSniffer – The PHP Coding Standards Tool
A couple of years ago I implemented a coding standards guide for PHP development at TMW, as I'd noticed that they only had a document that was focused on .Net and Windows. The guide outlined mostly common sense practices, such as avoiding certain unsafe language functions, and how to best indent and document your code. Just over a year ago I made this document public on the TMW GitHub account, and…
-
Labour of Love: Building a Framework
At the start of this year (2015) I embarked upon a small personal challenge which I'd set myself: could I build a PHP MVC framework in a week? I had a fairly quiet schedule at the time, and I believed it was possible, so I began. Now, I have had quite a few years experience using various frameworks, so I had a rough idea about how I wanted to go about structuring my own: Basic request router…
-
Writing a Better Profanity Filter in PHP
When you accept user-generated content on your website, you will, at one point of another, see content that you really wish you hadn't. This could be Joe Bloggs cursing at your article, or John Smith throwing out every insult imaginable in an attempt to goad you or your websites visitors. Usually in these situations you have a couple of options, full moderation or content filtering. It's the latter…
-
Using PHP to make a HEAD request to get a files size
I had a request recently to get the size of a large collection of files that were hosted on Amazons S3 storage and add the values to a database containing a list of these files that acted as a local cache. I saw two main ways to achieve this: mount the S3 storage and treat the files as if they were local, or query the files on the fly as the sizes are required. I went for the second method, which…
-
Roman to Decimal Conversion
I stumbled across a recent post on Stack Overflow where someone was asking how to convert from Roman numerals to decimal with PHP. The answers already there seemed more complicated than the ought to be, so I figured I'd write a quick function for it myself. This is only a very basic attempt, and doesn't take into account certain rules, like Roman digits which shouldn't be repeated, and what values…
-
Fixing the Headers Already Sent Error
This is probably the single most frequent error I've seen come up as part of a question on mailing lists and forums, usually when one moves a script from a more lenient server to one that is more strict in its error reporting. The issue is caused by some call to header() after some output is sent to the browser. What can be sometimes difficult to understand for programmers new to PHP is that HTML…
-
Smart Image Resizing
When creating any sort of dynamic gallery there is always the issue of creating thumbnails. This is not a problem if all of the source images are the same size, but with a dynamic gallery that cannot be guaranteed. Sure, you could leave instructions that images must be of a certain width and height, and reject anything that doesn't fit, but isn't it nicer to create smart thumbnails from any size and…
-
Remove Rubbish Microsoft Markup
This is an amendment to the function I wrote to fix the broken characters that Microsoft Office inserts into content that you paste into your CMS. The update adds an optional parameter to the function that can strip out the MS-specific styles that are only recognised by IE and cause display issues in other browsers. The problems caused by Microsoft because of this have been quite large, and have…
-
Creating Select Lists with Default Options
Select lists are great, but what happens when your visitor has made a mistake in the form and you need to re-display the form, along with the option they just selected? This is where PHP, comes in. Now, depending on how your site is set up, you might be creating the select list from either a database or other source, but at some point it will be in a form that you can loop though. For this example…
-
Stylesheet Switcher
One drawback to alternate stylesheets on a website is that no browser I've seen allows the newly selected stylesheet to persist through the browsing of that site. As you move from page to page, the default style takes over again. This was particularly annoying for me, as I was in the middle of testing out a new stylesheet on my site as a demonstration, and each time I navigated to a new page, I'd have…
-
Using cURL to Interface with Twitter
Twitter. Love it or hate it, it's here to stay for a while. One recent project I worked on required some integration between Twitter and the website in I was working on. Having only a short while to work on this, and not being familiar with any of the various plugins out there, I wrote a simple function using cURL. While this example will focus on grabbing the number of followers of MicroMart magazine…
-
Listing Directories In An FTP Location
A question that I saw recently on a mailing list was how to determine whether a file (I'll use the Unix terminology here: everything is a file) on an FTP connection is a directory or a file. One suggestion was to use the FTP file wrapper in PHP and then use the is_file() and is_dir() functions to determine the type. I noted at the time that this wasn't a perfect solution, as it relied on the FTP file…
-
Pass Values by Reference in foreach Loops
Quite often, the question comes up about how to modify elements of an associative array inside a foreach loop, because the foreach loop passes by value, essentially creating a duplicate array in memory which your code works on. While this is usually not an issue, it can be if you want to actually modify the array. There are two ways in which you can do this, use the key of each element to modify the…
-
Streaming Files for Security
Picture the scenario: You've just set up a social networking site for your niche hobby of collecting old tin cans. Part of the site is an image gallery that allows members to upload pictures of their collections. You want to make sure that only members can see these images, but how? Preventing access to a page that contains the image is easy, but what if they try to link to the image directly? One…
-
Replacing Non-Displaying MS Word Characters
I work on a lot of CMS's, and website content generally follows the same general process: Original copy is written, and saved as an MS Word document. This file is sent on for review and final edits. Content from final version is copied and pasted directly from Word into the CMS. Now generally, this process is fine. However, if any of a number of particular characters was used in the original…
-
Alternate Table Rows in PHP
I often see people asking around on forums and mailing lists, how best to create tables with alternate rows, and I often see a variety of methods, many of which are quite frankly scary! Sure, CSS3 has a pretty nifty solution in the form of the nth-child selector, but this has limited browser support (currently, it is not recognised by Firefox 2 & 3 or IE 6 & 7), and CSS3 has not yet been fully…
-
PHP Image Header
Despite efforts made by many groups to allow designers to embed fonts into their web pages, such as WEFT and CSS, no method has managed to achieve support across all the popular browsers. Currently, the CSS method looks the best bet, but is still too far in the distant future to be considered a viable option at the moment. Because of this, alternatives such as the Flash sIFR, but this relies on Flash…
-
Form Validation
Form validation is one of the most under-rated and at the same time most important parts of a web application. It might seem good at first to check for simple things like checking to see if an email address has an @ sign, or that a name field has more than 1 character, the truth is that without sanitising your inputs, you're leaving your whole website vulnerable to attack. Take a contact form as an…
-
PHP Calendar
The calendar at the right-hand side of the site is something which I am often asked about. I have seen many examples online, but all seemed needlessly complicated or coded in a particularly odd fashion. Having decided early on that something simple, efficiently scripted and easy to tweak was needed, I created the one which you see on the site. Here is the source code: <?php $ymDate =…
-
PHP Captcha
Spam is a huge problem on the Internet today, across the Web, Email, Newsgroups, to name but a few areas. Recently, spammers have been targeting websites, particularly forums, blogs and wikis. The tried and tested method to prevent this is to use a CAPTCHA. The idea goes back to Alan Turings idea of a test to differentiate humans and computers, which is now used to test AI. 1997, Andrei Broder devised…