Tag Archives: PHP

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

PHP: How to Convert a Timestamp into a Date String Programming 26 MAR 2015

Unix timestamps aren’t exactly human readable representations of time. After all, a Unix timestamp is the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Usually one wants to show this to a user in a much friendlier date time format, like the tried and trusted Y-m-d H:i:s standard, e.g. ‘2015-03-23 09:00’.

It turns out achieving this formatted display is relatively easy: just use the standard DateTime class!

You can use a timestamp as construct parameter if you add the @-sign at the front. Once that is done, simply use the format function to return a user friendly date/time string:

$dateTimeEnd = new DateTime('@1427105451'); 
echo $dateTimeEnd->format('Y-m-d H:i:s'); //prints 2015-03-23 10:10:51

Quick and simple.


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

PHP Regex Pattern Test Tool Software & Sites 05 DEC 2014

Annoyingly, my regex, even after all these years of web development, is still completely horrible – pretty much non-existent actually. Which is exactly why I always like to keep a handy regex pattern test tool on hand for the odd occasion when I do actually need to use the power of regular expressions.

Happily, Philip Bjorge saw fit to put together a cool little online PHP Regex test pad in the form of PHP Live Regex.

It’s simple to use, updates its regex results in realtime, and has a whole lot of helper text sitting at the bottom of the screen.

Quite a nice little implementation then in other words.


Related Link: http://www.phpliveregex.com/

PHP: The Danger of !strpos(‘something’, ‘something’) === FALSE Tips, Tricks and Tutorials 26 FEB 2014

green php elephants - elephpantsI came across some search and replace PHP code that was working correctly if the search string sat in the middle or towards the end of the input string, but failed to perform if the search string was positioned at the front of the string.

Taking a look at the function in question, I quickly spotted the mistake.

The coder had put down:

if (!strpos($inputstring,$searchstring) === false){
//search string located, so do something!

Now we know strpos returns the integer index of the starting point of the first instance of the search string if it locates the search string in the input string, or a boolean FALSE if it can’t locate it.

Based on this, the developer was essentially trying to say that IF (NOT ({strpos result} === FALSE)) (in other words the result is anything but FALSE) then we’ve found what we are looking for.

Unfortunately what tripped him up here was classic operator order – essentially his line of code means that the ! (NOT) is applied first to the result of strpos, before the result of that operation is compared to FALSE.

In other words, he wouldn’t suffer from the problem had he simply introduced some more brackets into his statement:

if (!(strpos($inputstring,$searchstring) === false)){
//search string located, so do something!

With these brackets in place, the function now basically gets the result of the strpos function and checks if it is equivalent to false, before flipping the answer by applying NOT (!) to it.

But why did the original approach find the search string as long as it wasn’t right at the start of the input string then?

Well the reason lies in PHP’s unfortunate ability to represent the boolean FALSE as the integer 0.

So, if the search string existed in the input string, but not at the start of the input string, the strpos function would return an integer greater than 0. This integer once flipped with NOT would result in a boolean FALSE, which would then satisfy the === FALSE check at the end, thus telling us the search string was present. If the search string wasn’t found, strpos would return FALSE, which would be flipped to become TRUE which then wouldn’t match the final check against FALSE, in other words correctly telling us that the search string does not exist.

However, if the search string was at the start of the input string, then strpos returned 0, which is as far a PHP is concerned, equal to FALSE. And flipping FALSE with NOT of course results in TRUE, which as expected, does not satisfy the final FALSE check and thus incorrect tells us that the search string is not present in the input string.

Now with the newly added brackets in place, the solution correctly first evaluates the strpos result against FALSE before flipping it with NOT, meaning that the function now works consistentl in terms of it doesn’t matter where the search string exists within the input string.

All of this said and done though, of course our dear developer could have completely sidestepped this mess had he simply evaluated the strpos result using !=== FALSE in the first place!