Tag: PHP

PHP: rounding a number and keeping the zeros after comma

In PHP you can use the round() method to round a double. This methods accepts a precision value as second parameter. Some examples:

echo round(3.1415926, 2); // "3.14"
echo round(3.1415926, 3); // "3.142"

When using round() on a value like 3.0000 the conversion to a string will result in just "3":

echo round(3.0000000, 2); // "3"

This is not wrong, but when you want to have a constant precision for different numbers, having an output of "3.00" is much more helpful.

To achieve this, you can use one of the following solutions.


echo number_format(3.1415926, 2); // "3.14"


echo sprintf("%.2f", 3.1415926); // "3.14"


PHP: get version details from composer.json

Let’s say we have a composer.json file as follows:

    "name": "mixable/blog",
    "description": "mixable.blog",
    "homepage": "https://mixable.blog",
    "version": "4.0.1",
    "type": "project",
    "require": {
        "php": "^8.x",
        "vendor/package": "^4.3",

When using this file to manage the packages of an app, it might be necessary to check for the version of your app. This is possible by using the Composer class \Composer\InstalledVersions. The class provides different methods to access the details of the projects composer.json file.

Get details about the root package

Details about the root package are available through the getRootPackage() method:

$package = \Composer\InstalledVersions::getRootPackage();

This method returns an array with the following details:

name: string
version: string
reference: string
pretty_version: string
aliases: string[]
dev: bool
install_path: string
type: string

To get the apps version, you can use:

$version = \Composer\InstalledVersions::getRootPackage()['version'];

Get details about installed packages

There is a number of methods that provide additional information about the installed packages. Some examples:

Version of an installed package

$version = \Composer\InstalledVersions::getVersion('vendor/package');

Install path of an installed package

$installPath = \Composer\InstalledVersions::getInstallPath('vendor/package');

A detailed description of all methods is available at https://getcomposer.org/doc/07-runtime.md#installed-versions.

Photo by Ilya Pavlov on Unsplash


PHP: realpath() for non-existing path

The php method realpath() can transform the string format of a path into a real path. Means, a path string like:


will become:


But this only works, if the path really exists. For non-existing paths, this function cannot be used. To get the same functionality, the following function can be used:

 * Get normalized path, like realpath() for non-existing path or file
 * @param string $path path to be normalized
 * @return false|string|string[]
public function normalizePath(string $path)
    return array_reduce(explode('/', $path), function($a, $b) {
        if ($a === null) {
            $a = "/";
        if ($b === "" || $b === ".") {
            return $a;
        if ($b === "..") {
            return dirname($a);

        return preg_replace("/\/+/", "/", "$a/$b");

How to ignore PHP_CodeSniffer warning: Line exceeds 120 characters;

When using codesniffer to check your code, a lot of warnings might appear when the lines are too long:

  73 | WARNING | Line exceeds 120 characters; contains 162 characters
  75 | WARNING | Line exceeds 120 characters; contains 124 characters
 102 | WARNING | Line exceeds 120 characters; contains 168 characters
 108 | WARNING | Line exceeds 120 characters; contains 121 characters

To ignore those warnings, we can add // phpcs:ignore as a comment to the end of a (too long) line. For example:

$message = 'This is my long message. It\'s not only long, it\'s extreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeemly long'; // phpcs:ignore

PNG – deactivate interlace to avoid ‘libpng warning: Interlace handling should be turned on when using png_read_image’

I stumbled appon a warning message that was thrown by PHP when handling images with GD lib (e.g. imagecreatefrompng()). The message shown was:

libpng warning: Interlace handling should be turned on when using png_read_image

This message even exists, when deactivating ‘interlace’ with the help of:

imageinterlace($img, false);

The point is that this message is not caused by any wrong php code, it is caused by the processed images itself. The only solution is to deactivate interlace for the processed image(s). This is possible with ImageMagick. To deactivate interlace on all images of a folder, the following command can be used:

magick mogrify -interlace none *.png

I used ImageMagick on macos and installed it with with HomeBrew:

brew install imagemagick

PHP ColorUtils

A neat collection of useful methods to convert colors between different color spaces is available on GitHub (MIT License). It can convert any values between RGB, HSL, CMYK, YUV and HEX colors.

I created a ready-to-use php class out of this method collection:



The methods itself are mostly self-explaining. To use the class, just include the php file into your script and you are ready to go:


The methods itself are static, they can be used like:

$hex = '#ffcc00';
$rgb = ColorUtils::hex2rgb($hex);

Which results in an array with three values (red, blue, green) in $rgb:

// [0 => 255, 1 => 204, 2 => 0]

Photo by Kelli Tungay on Unsplash

Fatal error: Call to undefined function bindtextdomain()

Fatal error: Call to undefined function bindtextdomain() in [...]

This error might be caused by a missing GetText extension. If this is the case, you have to enable the extension in your php.ini:


If the extension is not installed yet, this is how to install gettext on macOS (for PHP7.0):

sudo port install php70-gettext

Afterwards, do not forget to restart Apache:

sudo port unload apache2
sudo port load apache2

PHP: Wie bekommt man Gettext zum Laufen?

Zunächst erstellt man sich ein Verzeichnis, z.B. locales/, in dem die Übersetzungsdateien abgelegt werden. Die Verzeichnisstruktur sollte Unterverzeichnisse für jede Sprache, beispielsweise en/ für Englisch, de/ für Deutsch, usw. enthalten und wie folgt aufgebaut sein:


In diese Verzeichnisse kommen dann die Übersetzungsdateien (*.mo, *.po). Wie diese aufgebaut sind bzw erstellt werden, soll an dieser Stelle nicht weiter erläutert werden.

Einbindung in PHP

So sieht die Einbindung von Gettext in PHP aus:

$locale = 'de_DE';
$directory = './locales'; // diesen Pfad entsprechend anpassen!
$domain = 'default';

setlocale(LC_ALL, $locale.'.utf8');  // 'de_DE.utf8' (wichtig: utf8 ohne '-'!)
bindtextdomain($domain, $directory); // 'default', './locales'
textdomain($domain);                 // 'default'
bind_textdomain_codeset($domain, 'UTF-8');

Zu beachtende Punkte

Gettext funktioniert nicht wie gewünscht? Lokalisierung wird nicht angezeigt? Dies dann kann verschiedene Gründe haben. Hier ein paar Anmerkungen:

Der String in $locale muss eine gültige Lokalisierung sein, welche auch auf dem System zur Verfügung steht. Ist diese korrekt (bzw. existiert diese), dann gibt setlocale() true zurück, andernfalls false.

Im Fehlerfall sollte man also prüfen, ob das System die angegebene Lokalisierung auch bereitstellt. Das kann man der Ausgabe folgender Zeile entnehmen:


Das Encodings (UTF-8) muss bei setlocale() ohne jeglichen Bindestrich angegeben werden.

Die Angabe ‘default’ bezieht sich auf die Domain, also den Dateinamen der *.mo-Datei. Die *.po-Datei werden übrigens nicht direkt von Gettext verwendet. Diese werden aber benötigt, um die *.mo-Dateien zu erstellen.