Tag Archives: PHP

PHP: Get the first Key of an Associative Array Tips, Tricks and Tutorials 16 JUN 2018

I am not completely sure about it, but I somehow don’t think that I’ve ever needed to get the first key of an associative array using PHP before. Sure, a simple problem with a simple solution, but seeing as I needed to Google this one, I’m jotting down the answer here for future reference.

So, our example for the day then: Given the following array, print out the first key.

$months = array(

$result = key($months);
if ($result !== NULL){
echo $result; //this will print 'jan'

The important bits are reset(), which moves the internal array pointer back to the first element of the array, and then key(), which retrieves the index element at the current array position (dictated by the internal pointer).

Simple (when you read the documentation).

UPDATE: As pointed out by one of my readers, if you know you have an array with at least one element in it, you could always just use array_keys($months)[0] as an alternative.

Related Link: reset() | key()

PHP: “JPEG library reports unrecoverable error: Not a JPEG file: starts with 0x89 0x50” Error Solved Tips, Tricks and Tutorials 30 OCT 2017

My cross-platform Kinetica TouchandTell app running on an old iPad 3 was not successfully uploading images to our new RedStation hosted Ubuntu server (the Android builds were doing it just fine), and I wasn’t really sure why. The Appcelerator Titanium code seemed all okay and in fact it wasn’t until I checked the server’s PHP error logs that I finally spotted the reason why. Exhibit A:

“JPEG library reports unrecoverable error: Not a JPEG file: starts with 0x89 0x50”

Some quick Googling led me to understand that the PHP GD library was failing when trying to parse the received JPG file from the iPad, primarily because the supplied photo was not in the accepted JPEG format. (In fact, chances are that the encoding is in fact either that of a PNG file or perhaps the brand new HEIC image format that has just rolled out with iOS 11).

Although the documentation states that the old imagecreatefromjpeg function is meant to return FALSE if it fails to open the supplied file, there is (annoyingly) a listed bug tracking the fact that the function is in practice actually triggering a Fatal Error instead!

So instead of adopting a practice of trying to open an image based on its file extension, a better solution to get around this problem would be to make use of the similar imagecreatefromstring function, which returns an image resource representing the photo obtained from the given file.

In practice:

$image = false;
$image_data = file_get_contents($imagefilepath);
try {
      $image = imagecreatefromstring($image_data);
} catch (Exception $ex) {
      $image = false;
if ($image !== false){
//process $image resource

(These image types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, BMP, WBMP, and GD2.)

Related Link: imagecreatefromstring

Ubuntu Server: How To Enable OPcache for PHP 7 on Apache Tips, Tricks and Tutorials 23 OCT 2017

PHP is what is known as an interpreted coding language, meaning that unlike compiled apps that have already been compiled down into bytecode (i.e. you have to compile your application first so that the OS can run it), PHP scripts are only compiled and interpreted by the runtime engine on script request.

So, if you have scripts that are relatively static (i.e. you aren’t changing them very often), one good way to accelerate your PHP project is to use some sort of caching system that essentially pre-compiles your scripts down to bytecode, meaning less work come request time and thus theoretically, faster code execution.

Enter opcode caching. OPcache, originally a closed source part of the Zend Server project (under the moniker of Zend Optimizer), is an open source module that stores (caches) precompiled PHP script bytecode in shared memory, thus removing the need for PHP to first load and parse scripts on each request.

Since PHP 5.5.0, the module has come bundled with PHP (though disabled by default), meaning that for all intents and purposes, OPcache is now pretty much the standard when it comes to PHP accelerating.

To set up OPcache on an Ubuntu 16.04 server running PHP 7 over Apache, you first need to enable OPcache via the standard php.ini file. To edit the file:

sudo nano /etc/php/7.0/apache2/php.ini

To enable the module once you have the php.ini file is open, find the line reading ;opcache.enable=0, uncomment it by removing the ; and then enable by changing the 0 to 1:


There are quite a few OPcache related settings that you can change while doing the setup, with the php.ini doing a good job of explaining the role of each one. The important ones to keep track of are: opcache.memory_consumption, opcache.max_accelerated_files, and opcache_revalidate_freq.

Save your changes and then enable the module via:

sudo phpenmod opcache

Finally, restart PHP:

sudo service apache2 restart

Monitoring OPCache is a whole other story (worth a google), but the easiest way just to make sure that it is in fact running is to call phpinfo() on one of your webpages. If enabled, you’ll see a bold section under the title of Zend OPcache, with the first column “Opcode Caching” listing a value of “Up and Running”.

Related Link: PHP OPcache | Wikipedia

FPDF: How to use a Degree Symbol in a Generated PDF Tips, Tricks and Tutorials 29 SEP 2017

I’ve been using the FPDF PDF generator library for years now as the de facto method for my PHP projects to produce PDF reports. However, one minor annoyance is that the generated PDF files often falter when it comes to the inclusion of certain special characters – like the degree symbol (°) as an example.  (Basically, something like °C becomes °C in the final document)

The reason for this happening is that Arial, the default used/included font, is of type ISO-8859-1 while the degree symbol is UTF-8 encoded. So in order for us to include special symbols or characters from other languages, we need to either try and convert them into our font compatible ISO-8859-1 format, or perhaps switch to using a different TrueType or Type1 font (which then would contain the desired character set).

Now while UTF-8 support is available via a modified class, the easiest way to fix the degree symbol issue without having doing any real work is to simply make use of the PHP utf8_decode function, which convert UTF-8 encoded strings to their ISO-8859-1 equivalents.

In other words outputting utf8_decode(“°C”) to your PDF should result in the expected °C

Related Link: FPDF PDF Generator Library

PHP: Figure out which Function called Your Function Programming 03 JUL 2016

When troubleshooting code, it is often quite handy to know what function called the function that you are busy working your way through. To do this you need a backtrace, and PHP makes getting one pretty easy thanks to its debug_backtrace function.

If you are interested in only the calling function name itself, then this neat little function should work quite nicely:

function GetCallingFunctionName($debug = false) {
//Returns the calling function through a backtrace
        $r = '';
        $debugString = '';
        $caller = debug_backtrace();
        if ($debug === true) {
            $debugString.= ' <p>START: debug_backtrace result:</p>';
            $debugString.= '<pre>';
            $debugString.= print_r($caller, true);
            $debugString.= '</pre>';
            $debugString.= '<p>END: debug_backtrace result:</p>';
        $caller = $caller[2];
        $r .= $caller['function'] . '()';
        if (isset($caller['class'])) {
            $r .= ' in ' . $caller['class'];
        if (isset($caller['object'])) {
            $r .= ' (' . get_class($caller['object']) . ')';
        return $r . $debugString;

Worth jotting down for the next time a function is giving me a headache for no apparent reason!

one-handed backhand tennis shot

Related Link: debug_backtrace | Source 1

Solved: F3 Framework Route is running Twice Programming 02 JUL 2016

I’ve inherited a project written using the Fat-Free Framework (or F3 Framework), which is billed as being a lightweight PHP micro-framework that is intended to be easy-to-use and fast, with a gentle learning curve thrown in for good measure. (In fairness, all three of these points seem to be holding relatively true thus far…)

fat-free framework php

Anyway, the project was written by an outsourced Polish developer, and now that he is no longer available, I’m bringing it in-house and expanding on it. Of course, this means that I’m refactoring it a little bit to better suit my own coding style. However, I hit an annoying snag which embarrassingly held me up for far longer than what it should have.

After making a class/controller name change, I was testing my routing when it became apparent that all of a sudden, one of my routes was running it’s function call twice.

An annoying issue to say the least.

So just a heads up, before you tear your hair out – be sure that your target function does in fact not share the same name of your newly renamed class in which said function resides.

If it does, then the framework will call the function through the run() routing as expected, and following that, the function will be called again… because as you might have noticed by now, the fact that your function is the same name as the class means that it is of course a constructor function.

So yes. I’ve jotted this down as a reminder to myself, that sometimes I’m an idiot.

Related Link: Fat-Free Framework

PHPMailer: AddReplyTo not working/being ignored Tips, Tricks and Tutorials 15 JUL 2015

PHPMailer is a popular full-featured email creation and transfer class for PHP, and one that I most often use in my projects.

We recently spotted an issue whereby we were setting the AddReplyTo field to a mail object for send out, but on subsequent send, the mail clients seemed to all be ignoring what we had set as the e-mail address which “Reply To” should use! Essentially it was as if AddReplyTo is either not working or being ignored – more than just a little annoying indeed!

It turns out however that there was (or perhaps still is) an issue whereby if an e-mail address is set via the SetFrom call before you set the AddReplyTo call, the Reply To address is simply ignored when the e-mail headers are constructed. So a simple fix is to call AddReplyTo first, before calling SetFrom.

So in other words, the correct order should be:

$mail->AddReplyTo('replyto@email.com', 'Reply to name');
$mail->AddAddress('user@email.com', 'User name);
$mail->SetFrom('mailbox@email.com', 'Mailbox name');

This behaviour may have subsequently changed in newer versions of the PHPMailer class, but if you’re having the same issue that I was having, this is most definitely a quick and easy fix!

postman pat with boombox

Related Link: https://github.com/Synchro/PHPMailer

Error: Call to undefined function mcrypt_get_iv_size() Tips, Tricks and Tutorials 03 JUL 2015

I installed my web application onto a new version of Ubuntu Server, and noted almost immediately that the web application crashed on each login attempt. Consulting the Apache error log, the issue quickly became clear:

Call to undefined function mcrypt_get_iv_size()

It would seem that php_mcrypt.dll is no longer loaded on a default install, meaning that you need to enable the mcrypt module under apache/php. To do this is pretty easy:

sudo apt-get install php5-mcrypt
sudo php5enmod mcrypt
sudo service apache2 restart

Ran through those and everything was now up and running again – so worth noting for anyone else out there busy bashing their heads against a wall! :)


PHP: How to Convert a Date/Time from UTC to another Time Zone Programming 27 MAR 2015

Having previously shown you a useful way of quickly converting a timestamp into a formatted date string, here’s a quick way of actually getting a date/time in a time zone that you actually want – and again we turn to the powerfull PHP DateTime class to do this for us.

//here we'll use a UTC (time zone independent) time for our example
//(remember, time() always returns a UTC timestamp)
$dateTimeEnd = new DateTime('@' . time());
echo $dateTimeEnd->format('Y-m-d H:i:s');            
//now let's change to GMT+2 (SAST - South African Standard Time)
$dateTimeEnd->setTimezone(new DateTimeZone('Africa/Johannesburg'));
echo $dateTimeEnd->format('Y-m-d H:i:s');

As you can see, the setTimezone function of the DateTime class does all the heavy lifting for us, making it a snap to convert timestamps between different time zones.

Just a note, if you want to get the current time zone that your script is executing under, you can make use of date_default_timezone_get:

if (date_default_timezone_get()) {
    echo 'current time zone: ' . date_default_timezone_get() . '<br />';

A handy tip to remember then in other words!

world map showing time zones

Related Link: http://php.net/manual/en/class.datetime.php