Category: PHP Toggle Comment Threads | Keyboard Shortcuts

  • Jay Versluis 10:44 pm on November 29, 2016 Permalink | Reply

    Categories: Linux, PHP ( 96 )

    How to install PHP from source on CentOS 

    PHP-IconI have recently installed PHP 7 from source on a fresh minimal CentOS 7 box. No previous version of PHP was installed, and I thought I’d give 7 a spin. There were a few pitfalls I hadn’t come across before, so here’s what worked for me.

    Downloading and extracting the source code

    It sounds crazy, but this was the hardest part of the whole installation! There were two problems I’ve encountered here.

    The first was that PHP offer downloads via a mirror. A direct link may look something like this: This means that if we were to download this file using wget, it would be saved as “mirror”. Now what we want.

    So instead we can ask wget to give the download a different name using the -O parameter, like so:

    wget -O php7.tar.bz2

    This will save our file as php7.tar.bz2 instead. So far so good. Unpacking this file seems to be impossible. From what the internet tells me, this should be the correct way of extracting a tar.bz2 file:

    tar -jxvf php7.tar.bz2

    But that didn’t work, not matter how hard I tried. All I ever got was a “non-recoverable” error. Which sucks. In the end I extracted the file on my Mac, created a ZIP archive and downloaded that instead. Unnecessarily cumbersome and idiotic, but worked. Finally I had them on my CentOS box.

    Building the source code

    Jumping into the extracted directory, the configure command can prepare the build. At this stage I encountered an error:

    configure: error: xml2-config not found. Please check your libxml2 installation.

    This can be fixed by installing the libxml2-devel package (NOT libxml2 as the error would have you believe). Let’s do that and run configure again:

    yum install libxml2-devel

    Now we can run make, followed by make test to see if the installation is going to go well. This will take a few minutes.

    make test

    Feel free to skip “make test” if you’re in a hurry. In my case, after over 10.000 tests, PHP told me this:

    You may have found a problem in PHP.
    This report can be automatically sent to the PHP QA team at and
    This gives us a better understanding of PHP's behavior.
    If you don't want to send the report immediately you can choose
    option "s" to save it. You can then email it to later.

    Perplexed yet unfazed, I continued on and installed PHP anyway:

    make install

    And only moments later, PHP 7 was running on my CentOS system.

    php -v
    PHP 7.0.12 (cli) (built: Nov  8 2016 06:59:14) ( NTS )
    Copyright (c) 1997-2016 The PHP Group
    Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies

    Not sure what else to tell you.

  • Jay Versluis 12:11 pm on June 11, 2016 Permalink | Reply  
    Categories: PHP, WordPress ( 26 )

    How to set WordPress Categories depending on the Post Title 

    I was working on a project the other day that required to determine which category a new post would go into, depending on the post title. This was important because posts were automatically acquired without the web interface, and in this workflow there was no way to pick a category other than the default.

    In our case we wanted to use a post fix in the title to determine which category was to be picked: for example, if a post title would end with “_ONE”, it should end up in Category 1, and if it ends up with “_TWO” it would end up in Category 2.

    Thankfully there’s a hook called save_post that is called every time a post is updated. At this point we can check what the post title is, determine the post fix, and set the correct category. Here’s a function that does just that:

    function set_my_categories($post_ID) {
    	// grab the current title
    	$title = get_the_title($post_ID);
    	// set the category depending on the last four characters of the title
    	// _ONE = Category 1
    	// _TWO = Category 2
    	$postfix = substr($title, -4);
    	if ($postfix == '_ONE') {
    		wp_set_post_categories($post_ID, array(1));
    	if ($postfix == '_TWO') {
    		wp_set_post_categories($post_ID, array(2));
    add_action('save_post', 'set_my_categories');

    If a post fix is not present, the categories will not be changed.

    For this example I’m assuming that my categories are actually 1 and 2 on the system, something that’s not really the case. To determine the correct value set under wp_set_post_categories, I usually head over to Posts – Categories, select the category I want to use and check the URL of what WordPress gives me. Say the URL looks like this:

    then the tag_ID parameter hints that my category has an ID of 366, and that’s the value we need to use.

    And if a post needs to go into two categories, separate the category IDs with a comma like so:

    wp_set_post_categories($post_ID, array(2,3));

    Removing the post fix before the title is displayed

    Since our post fix is for internal purposes only, we may not want it to appear as part of the actual post title on the front page. But we also don’t want to remove it from every post once the category has been set and still have a reference in the admin interface. So the way to do it is to simply suppress it before out theme prints it out.

    The following code will do just that: if a post fix is present, curb the title. If not, leave the title unchanged.

    // curb title if we have a post fix
    $title = get_the_title();
    $postfix = substr($title, -4);
    if ($postfix == '_ONE' || $postfix == '_TWO') {
    	$title = substr($title, 0, -4);
    // use echo $title to print the post title in your theme

    And there we have it. The same principle can be used if your title contains a certain keyword and you want to use it to add the post to a particular category automatically.

  • Jay Versluis 10:00 am on December 4, 2014 Permalink | Reply  
    Categories: PHP ( 26 )

    How to create a redirect in PHP 

    Say you had, and you’d like it to automatically redirect to, do the following:

    // redirecting elsewhere

    Add the above to a file called index.php in As soon as someone visits your location, the browser redirects to the new URL.

    Courtesy of the Stackoverflow community:

  • Jay Versluis 8:50 am on March 20, 2014 Permalink | Reply

    Categories: PHP ( 26 )

    How to switch between several PHP versions in MAMP 2.x 

    mamp logoSometimes you need to test your projects against multiple versions of PHP.

    If you’re using MAMP that’s fairly easy to do: head over to the MAMP Start Screen, select Preferences and see two versions to choose from.

    Here I’m using MAMP 2.2 (even though 3.x has been released already) and I have PHP 5.2.17 and PHP 5.5.3.

    When I switch to the other version MAMP restarts and I can refresh my browser to see my project running on the other PHP version.

    Screen Shot 2014-03-20 at 08.31.06

    Screen Shot 2014-03-20 at 08.31.12

    That’s all good if I actually needed either version – but sadly 5.2.x is too old for me, and 5.5.x doesn’t quite work and is a bit too cutting edge. I need it to reflect my production environment.

    So what is a boy to do?

    (More …)

    • pepperstreet 6:37 pm on November 21, 2015 Permalink | Reply

      Hello, anyone tried to update and use PHP > 5.5.3 in MAMP 2.2 ?
      Would like to keep MAMP 2.2 and add a newer PHP version on my older laptop/OSX.
      Thanks in advance.

      • Jay Versluis 10:41 pm on November 21, 2015 Permalink | Reply

        Hi pepperstreet, I’ve only tried older versions and they worked a treat, 5.5.3 came pre-installed with MAMP and also worked well. I can also tell you that when you install MAMP 3, it will install itself alongside MAMP 2 so if you want to try even newer versions of PHP, see if MAMP 3 works for you (and if not, simply keep using MAMP 2).

        Hope this helps!

    • Philipp 4:08 am on January 5, 2016 Permalink | Reply

      This doesn’t seem to work with PHP 7. Checkbox is grayed out.

      • Jay Versluis 10:00 pm on January 5, 2016 Permalink | Reply

        Is this on Mamp 2 or 3?

    • Philipp 2:14 pm on January 6, 2016 Permalink | Reply

      I updated to MAMP 3.5 and it’s working now. Was previously on MAMP 3.2.1.

  • Jay Versluis 10:59 am on March 18, 2014 Permalink | Reply
    Tags: filesize, round   

    Categories: PHP ( 26 )

    How to check the size of a file in PHP 

    PHP-IconPHP has a handy function called filesize() which can help us display how big a file is.

    It does this in bytes by default, but with a bit of tinkering we can easily convert this into kilobytes or megabytes.

    Let’s first see how this works in bytes:

    $file = '/path/to/your/file';
    $filesize = filesize($file);
    echo "The size of your file is $filesize bytes.";

    Converting bytes into kilobytes works by dividing the value by 1024. PHP is very accurate and will give you 12 decimal digits – perhaps a little overkill. To avoid this we can make use of the round() function and specify how many digits of accuracy we’d like to display:

    $file = '/path/to/your/file';
    $filesize = filesize($file); // bytes
    $filesize = round($filesize / 1024, 2); // kilobytes with two digits
    echo "The size of your file is $filesize KB.";

    To display the value in megabytes we’ll simply divide by 1024 twice:

    $file = '/path/to/your/file';
    $filesize = filesize($file); // bytes
    $filesize = round($filesize / 1024 / 1024, 1); // megabytes with 1 digit
    echo "The size of your file is $filesize MB.";

    • Lorenz 5:47 am on August 6, 2017 Permalink | Reply

      You are the boss – i found the same script but 10 times longer! Super easy and compact thanks a lot!

  • Jay Versluis 10:00 am on March 18, 2014 Permalink | Reply
    Tags: pathinfo, scandir   

    Categories: PHP ( 26 )

    How to list a directory in PHP and only show ZIP files 

    web-find-iconI wanted to list a directory in PHP. At the same time, I wanted to make sure only files are listed – not subdirectories or dot directories.

    More specifically, I only wanted to include files with the ending .zip.

    Two tools come to the rescue here:

    • scandir() to list the directory and give us an array
    • and the super handy pathinfo() to check a file extension

    Here’s how I did it

    function list_zipfiles($mydirectory) {
    	// directory we want to scan
    	$dircontents = scandir($mydirectory);
    	// list the contents
    	echo '<ul>';
    	foreach ($dircontents as $file) {
    		$extension = pathinfo($file, PATHINFO_EXTENSION);
    		if ($extension == 'zip') {
    			echo "<li>$file </li>";
    	echo '</ul>';

    Call the function with the directory of your choice – give it a full path like /var/your/directory. Next scandir() creates an array of files and directories which we iterate over with a foreach loop. I’m also formatting the output as an unordered list, hence the presence of some HTML elements in the echo statements.

    The first thing we’ll do in the loop is to have a look at each file’s extension. If it is in fact “zip” then we’d like to list it. Other elements won’t show up.

    I hope it helps 😉

  • Jay Versluis 7:30 pm on March 17, 2014 Permalink | Reply  
    Categories: PHP ( 26 )

    How to test which HTML form button was pressed in PHP 

    execImagine you have a HTML form with several values and two buttons at the bottom. One could say “Do This” and the other “Do That”. How do you know which one was pressed by the user?

    It’s fairly easy – but I keep forgetting this time and time again. We do this by accessing the name attribute of the HTML button in PHP.

    Consider this HTML form:

    <input type="submit" name="button1" class="button-primary" value="Do This" />
    <input type="submit" name="button2" class="button-secondary" value="or Do That" />

    The button classes are WordPress standard “blue” and “grey” button layouts, and the value is what’s written on the button. The secret sauce however is in the name fields here.

    Back in PHP when the form is submitted we can access the $_POST variable which an array of values we’re getting back from the form. We can access them like this:

    if (isset($_POST['button1'])) {
      // Do This was pressed
    } else if (isset($_POST['button2'])) {
      // Do That was pressed

    You can access the rest of your form’s elements in the same way (i.e. tick boxes, select options, text fields, etc).

  • Jay Versluis 7:13 pm on March 17, 2014 Permalink | Reply
    Tags: zip   

    Categories: PHP ( 26 )

    How to create a recursive ZIP Archive from a directory in PHP 

    PHP-IconI’ve just realised how (relatively) easy it is to make PHP create a ZIP Archive from a directory and its sub directories.

    Previously I had relied on the Linux Shell Command zip or tar to do this which is a convenient one liner. I had assumed that in PHP we had to go through each directory and add the files manually – until I’ve discovered the RecursiveIterator class variants.

    In this example I’m defining a root path and a file name for my archive (change at will), then iterate through each file in each directory (and if thats’ a directory too, we’ll go one level deeper). The result of which is an array of files. We’ll get their full paths and add them to the ZIP archive.

    // define some basics
    $rootPath = './';
    $archiveName = '';
    // initialize the ZIP archive
    $zip = new ZipArchive;
    $zip->open($archiveName, ZipArchive::CREATE);
    // create recursive directory iterator
    $files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
    // let's iterate
    foreach ($files as $name => $file) {
    	$filePath = $file->getRealPath();
    // close the zip file
    if (!$zip->close()) {
    	echo '<p>There was a problem writing the ZIP archive.</p>';
    } else {
    	echo '<p>Successfully created the ZIP Archive!</p>';

    The above will produce a ZIP file which will contain references to the absolute full paths of each file. That’s great if you’d like to unzip those files later in exactly the same location – but it’s not so cool if you’re just interested in the content and the idea of 11 sub folders strikes you as “less funny”.

    Help is at hand, thanks to the way we can add files to the archive – namely by creating a new local filename. Here’s an example of how this works on Linux systems:

    // let's iterate and create a new local file name
    foreach ($files as $name => $file) {
    	$new_filename = substr($name,strrpos($name,'/') + 1);
    	$zip->addFile($file, $new_filename);

    No more references to absolute full paths in your ZIP file.

  • Jay Versluis 5:23 pm on March 13, 2014 Permalink | Reply  
    Categories: PHP ( 26 )

    How to add elements to an array in PHP 

    PHP-IconIt’s extremely easy to add elements to an existing array in PHP – so easy in fact that I regularly forget how to do it!

    I’m used to initialising and setting up my variables from Objective C, but PHP is so much easier and deals with it on the fly. Here we do it – ideal for loops:

    // create the array
    $myArray = array();
    // add three elements to it
    $myArray[] = 'Hello';
    $myArray[] = 'I must';
    $myArray[] = 'be going';
    // loop through all elements
    foreach ($myArray as $item) {
      echo $item;

  • Jay Versluis 5:54 pm on February 21, 2014 Permalink | Reply
    Tags: ,   

    Categories: PHP ( 26 )

    Getting Started with ZEND Server 6 on Mac OS X 


    I’ve just installed ZEND Server 6.3 on my MacBook running Mavericks 10.9.1. Needless to say I’m sill a little shaken up from the huge amount of brain pain this adventure has caused.

    Because once downloaded and installed on your system, you may ask yourself a vital question: Now What?

    Let’s find out. This article is Work in Progress – bear with me while I flesh it out.

    The Basics

    ZEND Server on Mac is located here:

    • /usr/local/zend/

    Your web files live here:

    • /usr/local/zend/apache2/htdocs

    To open this directory in Finder you can navigate there with a Terminal session and open it, like so:

    cd /usr/local/zend/apache2/htdocs
    open .

    Now you can create a shortcut on your sidebar for easy access.

    To access the ZEND Server Admin interface, navigate to the following URL in your browser:

    If you’re done with it, you can uninstall ZEND Server with the following command:

    sudo /usr/local/zend/bin/

    (More …)

    • Yonni 10:28 am on February 26, 2014 Permalink | Reply

      Mysql access – you can deploy phpmyadmin from within the Zend Server UI’s Guide Page. After launching Zend Server, this is the first page that opens up and is the homepage for Zend Server’s UI.

      Right at the top, in Getting Started you have a scrolling gallery of applications, one of which is phpmyadmin.

      Deploy, configure, rejoice

      • Jay Versluis 9:17 am on February 27, 2014 Permalink | Reply

        Hi Yonni,

        Thank you so much for the tip – how could I have missed that 🙂 I hadn’t spotted there was a second page for applications!

        My first attempt to deploy phpMyAdmin manually didn’t work, but auto deploy via ZEND Server was indeed a breeze. Thanks for sharing!

compose new post
next post/next comment
previous post/previous comment
show/hide comments
go to top
go to login
show/hide help
shift + esc