Category: PHP

  • The Most Common Mistakes CakePHP Developers Make : A Tutorial for Beginners

    CakePHP is an amazing PHP framework, but it has a steep learning curve! It requires a good amount of research and training to become an expert.
    I have been fortunate to use CakePHP for over 7 years now, and in that time I’ve had the honor of working with many members of the CakePHP community.
    In this CakePHP tutorial I’d like to describe few bad practices which I have seen over the years, and propose the correct approach to avoid these mistakes. This isn’t to say my code is perfect, but as a programmer we are always learning, so it is important to follow the best practices and adjust as you learn!
    Content of this article is inspired by a post from CakeCoded. If you would like to learn more about CakePHP please visit our learning section here.
    This beginner CakePHP tutorial will help you avoid frying your CakePHP code with errors and mistakes!

    Common Mistake #1: Not Following CakePHP Coding Conventions

    CakePHP coding conventions can be viewed here. I will highlight a few things which I often notice when viewing other programmers’ code.
    Control structures. So often you see programmers get this wrong, and in some cases bring practices from other coding languages. CakePHP expects the following syntax:

    if ((expr_1) || (expr_2)) {
        // action_1;
    } elseif (!(expr_3) && (expr_4)) {
        // action_2;
    } else {
        // default_action;
    }
    

    There should be 1 (one) space before the first parenthesis and 1 (one) space between the last parenthesis and the opening bracket. So this means that the following is incorrect:

    if($this->request->data){
    }
    

    Note the spacing between the if and (, and between ) and {
    Always use curly brackets in control structures, even if they are not needed. They increase the readability of the code, and they give you fewer logical errors.
    So, for example, the following is incorrect:

    if ($foo)
        $bar = true
    

    This should be formatted like this:

    if ($foo) {
        $bar = true
    }
    

    Finally, watch where you place the brackets. Opening brackets shouldn’t start a new line. And make sure all your brackets line up so that each new bracket is in line with the closing bracket.
    Here are some incorrect examples:

    if ($foo)
    {
        $bar = true;
    }
    

    This is incorrect, the opening bracket should be in the first line:

    if ($foo) {
        $bar = true;
    if ($action) {
        $to = false;
    }
    }
    

    The indentation needs to line up correctly.
    I often hear programmers say, “But I am too busy to make the code neat….” My response is, “Trust me, neat code will stand the test of time”. Writing CakePHP code which isn’t readable will be a nightmare to come back to if you need to make a change in a few months.

    Common Mistake #2: Improper Use of Containable Behaviors and Recursive Levels in ORM

    I was fortunate recently to have an informal discussion with a database developer from Facebook. We started talking about CakePHP and he said to me, “Oh, that uses ORM doesn’t it? That can be scary.” I asked him what he meant, and he commented that with Object-relational mapping (ORM) it is easy for SQL queries to become unnecessarily large.
    He is right in a way. Part of CakePHP’s magic is in its use of ORM and the way that it groups different database table relations together. By default, CakePHP automatically selects any related ‘Belongs To’, ‘Has One’ and ‘Has Many’ data, and this can lead to very large SQL queries. These queries may not be a concern when you are initially developing an application, but after six months of collecting live data, you may find the application becomes very slow, and in some cases crashes if the queries aren’t optimized.
    I look out for two things when auditing an existing website. Firstly, has the default recursive level been changed? By default, CakePHP sets the recursive level to 1, which in my opinion is too high. I always set it to -1 and then use the containable behavior to get any related models.
    That leads to the second thing I look for – has the Containable behavior been used? I often have new clients come to me and say that CakePHP is slow. The reason is almost always because Containable hasn’t been used! A good CakePHP programmer will optimize their SQL queries regardless of how much “auto-magic” is done behind the scenes.
    The containable behavior wasn’t added until CakePHP 1.2, but boy has it made a difference?! Be sure to use containable as much as possible, as it is such an effective way to optimize your SQL. For more information on how to implement and use the Containable behavior, click here.

    Common Mistake #3: Keeping Business Logic in Controllers Instead of Models

    Good CakePHP code will have the logic in the model files. This takes a bit to get used to, but once mastered there is no looking back! A controller file should be used for what it is intended for in the MVC pattern – controlling! So use your controller file to handle user actions, while letting the business logic go in the model file.
    A good example of this would be a simple CRUD – an everyday action! Let’s take the add posts function from a blog tutorial as an example. The default add function is as follows:

    public function add() {
        if ($this->request->is('post')) {
            $this->Post->create();
            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash(__('Your post has been saved.'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('Unable to add your post.'));
        }
    }
    

    This controller action is fine for a simple add, but what would happen if you wanted to do things such as send an email to the admin when a post was added, or update another model association when a post was added. This is additional logic, but this logic shouldn’t go into our controller file.
    Instead we would write a function for this in our Post.php model. Perhaps something like this:

    public function addPost($data = array(), $emailAdmin = true) {
        $this->create();
        $this->save($data);
        // update any other tables
        // send the email to the admin user
        if ($emailAdmin) {
        }
        // if all is successful
        return true;
    }
    

    This would then result in a small change to the controller action as follows:

    public function add() {
        if ($this->request->is('post')) {
            if ($this->Post->addPost($this->request->data)) {
                $this->Session->setFlash(__('Your post has been saved.'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('Unable to add your post.'));
        }
    }
    

    As you can see, the new action is actually one less line, because the $this->Post->create() has been moved to the model file.
    This is a perfect, everyday example of where moving logic to the model file is a good idea – and it certainly makes for a much cleaner code base!

    Common Mistake #4: Adding Too Much Complexity to the Code, Instead of Returning Often and Early

    This is always a bit of an ongoing debate, but returning often, and returning early certainly does make for much cleaner looking code. This applies to the model methods more than anything else.
    But what exactly do I mean? Well, let’s take a look at the method we added in the CakePHP tutorial above:

    public function addPost($data = array(), $emailAdmin = true) {
        $this->create();
        $this->save($data);
        // update any other tables
        // send the email to the admin user
        if ($emailAdmin) {
        }
        // if all is successful
        return true;
    }
    

    To return often, and return early means that as we run through our function, we check to make sure the everything is OK on a regular basis. If it isn’t, then we return false, or return a CakePHP error.
    It might be easiest to show this with an example. There are two ways the above function could be written:

    public function addPost($data = array(), $emailAdmin = true) {
        if ($data) {
            $this->create();
            $result = $this->save($data);
            if ($result) {
                // update any other tables
                // send the email to the admin user
                if ($emailAdmin) {
                    // send the admin email
                }
            } else {
                // problem saving the data
                return false;
            }
            // if all is successful
            return true;
        } else {
            // no data submitted
            return false;
        }
    }
    

    See how the code quickly becomes unreadable? There are ifs and elses all over the place, and the function quickly becomes one big indentation. Don’t get me wrong, I love clean indentation, but watch how the function looks if it written with the return often, return early principle.

    public function addPost($data = array(), $emailAdmin = true) {
        if (!$data) {
            // no data submitted
            return false;
        }
        $this->create();
        $result = $this->save($data);
        if (!$result) {
            // problem saving the data
            return false;
        }
        // update any other tables
        // send the email to the admin user
        if ($emailAdmin) {
            // send the admin email
        }
        // if all is successful
        return true;
    }
    

    Straight away, in this small example, you can see the code only has a single indentation and is much more readable. The logic actually makes more sense – let the logic run through line by line, and if there is any issue along the way, return the error and don’t proceed to the next line.
    This allows a CakePHP programmer to write the same way that we read – reading code from left to right, top to bottom, rather than in different blocks, which can quickly get confusing!

    Common Mistake #5: Not Using the DRY Principle

    DRY stands for Don’t Repeat Yourself, and it is a philosophy which should be followed when coding in CakePHP. With object-oriented code, there is no excuse for repeating the same block of code twice!
    Here are few CakePHP tips to ensure you don’t repeat yourself:

    • As mentioned above, aim to put logic in model files so you can share the logic.
    • In your view files, if you are repeating views, create the view code as an Element, or even a custom helper.
    • Set up some configuration settings – the app/Config/bootstrap.php file is a great place for this. This helps make sure you aren’t hard coding things like the application name and the main email address. The last thing you want to do is go through hundreds of files just because the client has asked to update an email address in an application.
    • Always ask yourself, “If I am repeating code, is there a better way to write this code, and am I putting this code in the right place?” Chances are, if you need to repeat code, it could be written better.

    Common Mistake #6: Not Commenting the Code

    The last point I will make is in regards to comments. Firstly, doc blocking. A doc block is when you document a method or an action. It takes only a minute to record a little about what a function is doing, but it makes such a difference in terms of readability of code.
    CakePHP Doc Blocks need to go against the left margin of the page. So a simple example using the code from above.

    /**
     * Adds & saves a post as well as emails the admin to let them know the post has been added.
     * Also performs some saving to another table
     *
     * @param   array $data The post data
     * @param   bool $emailAdmin If set to true, will email the website admin
     * @return  bool Returns true if successful
     */
    public function addPost($data = array(), $emailAdmin = true) {
    

    As you will see, it doesn’t take long to write a doc block, but it makes a huge difference in terms of longevity of the code. Ultimately, it means the code can live on past you as the developer.
    Likewise with in-line comments. Don’t be scared to explain what your code is doing and why! It makes it a lot easier in the long run to understand your code, especially if another developer is looking at it!

    Wrap-up

    CakePHP is an extensive, full-featured framework. Given it follows convention over configuration, CakePHP is more strict than other PHP based frameworks, in the sense that a user is “forced” to follow a certain way of laying out the code. This can be controversial, but in my experience it leads to a code base which is more consistent, readable and understandable – rather than letting a developer “choose” how the code should be written, a development team will write consistent code by following Cake’s conventions.
    By following this CakePHP tutorial and ensuring your code is well written, applications can stand the test of time. Code should always be written for tomorrow – so that if another developer is looking at a particular code block years later, he will understand the code, and stick to the expected standards. CakePHP is no different and hopefully this guide will help correct some bad habits.

  • Data Encoding: A Guide to UTF-8 for PHP and MySQL

    As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8.

    A Quick UTF-8 Primer

    Unicode is a widely-used computing industry standard that defines a comprehensive mapping of unique numeric code values to the characters in most of today’s written character sets to aid with system interoperability and data interchange.
    UTF-8 is a variable-width encoding that can represent every character in the Unicode character set. It was designed for backward compatibility with ASCII and to avoid the complications of endianness and byte order marks in UTF-16 and UTF-32. UTF-8 has become the dominant character encoding for the World Wide Web, accounting for more than half of all Web pages.
    UTF-8 encodes each character using one to four bytes. The first 128 characters of Unicode correspond one-to-one with ASCII, making valid ASCII text also valid UTF-8-encoded text. It is for this reason that systems that are limited to use of the English character set are insulated from the complexities that can otherwise arise with UTF-8.
    For example, the Unicode hexidecimal code for the letter A is U+0041, which in UTF-8 is simply encoded with the single byte 41. In comparison, the Unicode hexidecimal code for the character  is U+233B4, which in UTF-8 is encoded with the four bytes F0 A3 8E B4.

    On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not.
    This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and so on. Soon, we ended up with a list of 600,000 artist bios with double- or triple-encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.
    Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pulling experience. This post provides a concise cookbook for addressing these issues when working with PHP and MySQL in particular, based on practical experience and lessons learned (and with thanks, in part, to information discovered here and here along the way).
    Data encoding with UTF-8 unicode for PHP and MySQL makes complex languages simple.
    Specifically, we’ll cover the following in this post:

    • Mods you’ll need to make to your php.ini file and PHP code.
    • Mods you’ll need to make to your my.ini file and other MySQL-related issues to be aware of (including config mods needed if you’re using Sphinx)
    • How to migrate data from a MySQL database previously encoded in latin1 to instead use a UTF-8 encoding

    PHP & UTF-8 Encoding – modifications to your php.ini file:

    The first thing you need to do is to modify your php.ini file to use UTF-8 as the default character set:

    	default_charset = "utf-8";
    

    (Note: You can subsequently use phpinfo() to verify that this has been set properly.)
    OK cool, so now PHP and UTF-8 should work just fine together. Right?
    Well, not exactly. In fact, not even close.
    While this change will ensure that PHP always outputs UTF-8 as the character encoding (in browser response Content-type headers), you still need to make a number of modifications to your PHP code to make sure that it properly processes and generates UTF-8 characters.

    PHP & UTF-8 Encoding – modifications to your code:

    To be sure that your PHP code plays well in the UTF-8 data encoding sandbox, here are the things you need to do:

    • Set UTF-8 as the character set for all headers output by your PHP codeIn every PHP output header, specify UTF-8 as the encoding:
        header('Content-Type: text/html; charset=utf-8');
      
    • Specify UTF-8 as the encoding type for XML
        <?xml version="1.0" encoding="UTF-8"?>
      
    • Strip out unsupported characters from XMLSince not all UTF-8 characters are accepted in an XML document, you’ll need to strip any such characters out from any XML that you generate. A useful function for doing this (which I found here) is the following:
        function utf8_for_xml($string)
        {
          return preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',
                              ' ', $string);
        }
      

      Here’s how you can use this function in your code:

        $safeString = utf8_for_xml($yourUnsafeString);
      
    • Specify UTF-8 as the character set for all HTML contentFor HTML content, specify UTF-8 as the encoding:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      

      In HTML forms, specify UTF-8 as the encoding:

        <form accept-charset="utf-8">
      
    • Specify UTF-8 as the encoding in all calls to htmlspecialcharse.g.:
        htmlspecialchars($str, ENT_NOQUOTES, "UTF-8")
      

      Note: As of PHP 5.6.0, default_charset value is used as the default. From PHP 5.4.0, UTF-8 was the default, but prior to PHP 5.4.0, ISO-8859-1 was used as the default. It’s therefore a good idea to always explicitly specify UTF-8 to be safe, even though this argument is technically optional.
      Also note that, for UTF-8, htmlspecialchars and htmlentities can be used interchangeably.

    • Set UTF-8 as the default character set for all MySQL connectionsSpecify UTF-8 as the default character set to use when exchanging data with the MySQL database using mysql_set_charset:
        $link = mysql_connect('localhost', 'user', 'password');
        mysql_set_charset('utf8', $link);
      

      Note that, as of PHP 5.5.0, mysql_set_charset is deprecated, and mysqli::set_charset should be used instead:

        $mysqli = new mysqli("localhost", "my_user", "my_password", "test");
        /* check connection */
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
        /* change character set to utf8 */
        if (!$mysqli->set_charset("utf8")) {
            printf("Error loading character set utf8: %s\n", $mysqli->error);
        } else {
            printf("Current character set: %s\n", $mysqli->character_set_name());
        }
        $mysqli->close();
      
    • Always use UTF-8 compatible versions of string manipulation functionsThere are several PHP functions that will fail, or at least not behave as expected, if the character representation needs more than 1 byte (as UTF-8 does). An example is the strlen function that will return the number of bytes rather than the number of characters.
      Two options are available for dealing with this:

      • The iconv functions that are available by default with PHP provide multibyte compatible versions of many of these functions (e.g., iconv_strlen, etc.). Remember, though, that the strings you provide to these functions must themselves be properly encoded.
      • There is also the mbstring extension to PHP (information on enabling and configuring it is available here). This extension provides a comprehensive set of functions that properly account for multibyte encoding.

    MySQL & UTF-8 Encoding – modifications to your my.ini file:

    On the MySQL/UTF-8 side of things, modifications to the my.ini file are required as follows:

    • Set the following config parameters after each corresponding tag:
        [client]
        default-character-set=UTF-8
        [mysql]
        default-character-set=UTF-8
        [mysqld]
        character-set-client-handshake = false #force encoding to uft8
        character-set-server=UTF-8
        collation-server=UTF-8_general_ci
        [mysqld_safe]
        default-character-set=UTF-8
      
    • After making the above changes to your my.ini file, restart your MySQL daemon.
    • To verify that everything has properly been set to use the UTF-8 encoding, execute the following query:
        mysql> show variables like 'char%';
      

      The output should look something like:

            | character_set_client        | UTF-8
            | character_set_connection    | UTF-8
            | character_set_database      | UTF-8
            | character_set_filesystem    | binary
            | character_set_results       | UTF-8
            | character_set_server        | UTF-8
            | character_set_system        | UTF-8
            | character_sets_dir          | /usr/share/mysql/charsets/
      

      If you instead see latin1 listed for any of these, double-check your configuration and make sure you’ve properly restarted your mysql daemon.

    MySQL & UTF-8 Encoding – other things to consider:

    • MySQL UTF-8 is actually a partial implementation of the full UTF-8 character set. Specifically, MySQL UTF-8 data encoding uses a maximum of 3 bytes, whereas 4 bytes are required for encoding the full UTF-8 character set. This is fine for all language characters, but if you need to support astral symbols (whose code points range from U+010000 to U+10FFFF), those require a four byte encoding which is not supported in MySQL UTF-8.  In MySQL 5.5.3, this was addressed with the addition of support for the utf8mb4 character set which uses a maximum of four bytes per character and thereby supports the full UTF-8 character set. So if you’re using MySQL 5.5.3 or later, use utf8mb4 instead of UTF-8 as your database/table/row character set. More info is available here.
    • If the connecting client has no way to specify the encoding for its communication with MySQL, after the connection is established you may have to run the following command/query:
        set names UTF-8;
      
    • When determining the size of varchar fields when modeling the database, don’t forget that UTF-8 characters may require as many as 4 bytes per character.

    MySQL & UTF-8 Encoding – if you use Sphinx:

    • In your Sphinx configuration file (i.e., sphinx.conf):
      • Set your index definition to have:
        charset_type = utf-8
        
      • Add the following to your source definition:
        sql_query_pre = SET CHARACTER_SET_RESULTS=UTF-8
        sql_query_pre = SET NAMES UTF-8
        
    • Restart the engine and remake all indices.
    • If you want to configure sphinx so that letters like C c Ć ć Ĉ ĉ Ċ ċ Č č are all treated as equivalent for search purposes, you will need to configure a charset_table (a.k.a. character folding) which is essentially an equivalency mapping between characters. More information is available here.

    MySQL – Migrating a database data that is already encoded in latin1 to UTF-8

    If you have an existing MySQL database that is already encoded in latin1, here’s how to convert the latin1 to UTF-8:

    1. Make sure you’ve made all the modifications to the configuration settings in your my.ini file, as described above.
    2. Execute the following command:
       ALTER SCHEMA `your-db-name` DEFAULT CHARACTER SET UTF-8;
      
    3. Via command line, verify that everything is properly set to UTF-8
       mysql> show variables like 'char%';
      
    4. Create a dump file with latin1 encoding for the table you want to convert:
       mysqldump -u USERNAME -pDB_PASSWORD --opt --skip-set-charset --default-character-set=latin1
                 --skip-extended-insert DATABASENAME --tables TABLENAME >
                 DUMP_FILE_TABLE.sql
      

      e.g:

       mysqldump -u root --opt --skip-set-charset  --default-character-set=latin1
                 --skip-extended-insert artists-database --tables tbl_artist >
                 tbl_artist.sql
      
    5. Do a global search and replace of the charset in the dumpfile from latin1 to UTF-8:e.g., using Perl:
       perl -i -pe 's/DEFAULT CHARSET=latin1/DEFAULT CHARSET=UTF-8/' DUMP_FILE_TABLE.sql
      

      Note to Windows users: This charset string replacement (from latin1 to UTF-8) can also be done using find-and-replace in WordPad (or some other text editor, such as vim). Be sure to save the file just as it is though (don’t save it as unicode txt file!).

    6. From this point, we will start messing with the database data, so it would probably be prudent to backup the database if you haven’t already done so. Then, restore the dump into the database:
       mysql> source "DUMP_FILE_TABLE.sql";
      
    7. Search for any records that may not have converted properly and correct them. Since non-ASCII characters are multi-byte by design, we can find them by comparing the byte length to the character length (i.e., to identify rows that may hold double-encoded UTF-8 characters that need to be fixed).
      • See if there are any records with multi-byte characters (if this query returns zero, then there don’t appear to be any records with multi-byte characters in your table and you can proceed to Step 8).
          mysql> select count(*) from MY_TABLE where LENGTH(MY_FIELD) != CHAR_LENGTH(MY_FIELD);
        
      • Copy rows with multi-byte characters into a temporary table:
          create table temptable (
              select * from MY_TABLE where
              LENGTH(MY_FIELD) != CHAR_LENGTH(MY_FIELD));
        
      • Convert double-encoded UTF-8 characters to proper UTF-8 charactersThis is actually a bit tricky. A double encoded string is one that was properly encoded as UTF-8. However, MySQL then did us the erroneous favor of converting it (from what it thought was latin1) to UTF-8 again, when we set the column to UTF-8 encoding. Resolving this therefore requires a two step process through which we “trick” MySQL in order to preclude it from doing us this “favor”.
        First, we set the encoding type for the column back to latin1, thereby removing the double encoding:
        e.g.:

          alter table temptable modify temptable.ArtistName varchar(128) character set latin1;
        

        Note: Be sure to use the correct field type for your table. In the example above, for our table, the correct field type for ‘ArtistName’ was varchar(128), but the field in your table could be text or any other type. Be sure to specify it properly!
        The problem is that now, if we set the column encoding back to UTF-8, MySQL will run the latin1 to UTF-8 data encoding for us again and we’ll be back to where we started. To avoid this, we change the column type to blob and THEN we set it to UTF-8. This exploits the fact that MySQL will not attempt to encode a blob. We are thereby able to “fool” the MySQL charset conversion to avoid the double encoding issue.
        e.g.:

          alter table temptable modify temptable.ArtistName blob;
          alter table temptable modify temptable.ArtistName varchar(128) character set UTF-8;
        

        (Again, as noted above, be sure to use the proper field type for your table.)

      • Remove rows with only single-byte characters from the temporary table:
          delete from MY_TABLE where LENGTH(MY_FIELD) = CHAR_LENGTH(MY_FIELD);
        
      • Re-insert fixed rows back into the original table (before doing this, you may want to run some selects on the temptable to verify that it appears to be properly corrected, just as a sanity check).
          replace into MY_TABLE (select * from temptable);
        
    8. Verify the remaining data and, if necessary, repeat the process in step 7 (this could be necessary, for example, if the data was triple encoded). Further errors, if any, may be easiest to resolve manually.

    Source code and resource files

    One other thing to remember and verify is that your source code files, resources files, and so on, are all being saved properly with UTF-8 data encoding. Otherwise, any “special” characters in these files may not be handled correctly.
    In Netbeans, for example, you can right-click on your project, choose properties and then in “Sources” you will find the data encoding option (it usually defaults to UTF-8, but it’s worth checking).
    Or in Windows Notepad, use the “Save As…” option in the File menu, and select the UTF-8 encoding option at the bottom of the dialog. (Note that the “Unicode” option that Notepad provides is actually UTF-16, so that’s not what you want.)

    Wrap-up

    Although it can be somewhat tedious, taking the time to go through these steps to systematically address your MySQL and PHP UTF-8 data encoding issues can ultimately save you a great deal of time and grief. In the long run, this type of methodical approach is far superior to the all-too-common tendency to just keep patching the system.
    This guide hopefully emphasizes the importance of taking the charset definition into consideration when setting up a project environment in the first place and working in a software project environment that properly accounts for character encoding in its manipulation of text and strings.

  • Building REST API for Legacy PHP Projects

    Building or architecting a REST API is not an easy task, especially when you have to do it for legacy PHP projects. There are a lot of 3rd party libraries nowadays that make it easy to implement a REST API, but integrating them into existing legacy codebases can be rather daunting. And, you don’t always have the luxury to work with modern frameworks, such as Laravel and Symfony. With legacy PHP projects, you can often find yourself somewhere in the middle of deprecated in-house frameworks, running on top of old versions of PHP.
    Building REST API for Legacy PHP Projects

    Building REST API for Legacy PHP Projects

    In this article, we will take a look at some common challenges of trying to implement REST APIs from scratch, a few ways to work around those issues and an overall strategy for building custom PHP based API servers for legacy projects.
    Although the article is based on PHP 5.3 and above, the core concepts are valid for all versions of PHP beyond version 5.0, and can even be applied to non-PHP projects. Here, we will not cover what a REST API is in general, so if you’re not familiar with it be sure to read about it first.
    To make it easy for you to follow along, here is a list of some terms used throughout this article and and their meanings:

    • API server: main REST application serving the API, in this case, written in PHP.
    • API endpoint: a backend “method” which the client communicates with to perform an action and produce results.
    • API endpoint URL: URL through which the backend system is accessible to the world.
    • API token: a unique identifier passed via HTTP headers or cookies from which the user can be identified.
    • App: client application which will communicate with the REST application via API endpoints. In this article we will assume that it is web based (either desktop or mobile), and so it is written in JavaScript.

    Initial Steps

    Path Patterns

    One of the very first things that we need to decide is at what URL path the API endpoints will be available. There are 2 popular ways:

    • Create a new subdomain, such as api.example.com.
    • Create a path, such as example.com/api.

    At a glance, it may seem that the first variant is more popular and attractive. In reality, however, if you’re building a project-specific API, it could be more appropriate to choose the second variant.
    One of the most important reasons behind taking the second approach is that this allows cookies to be used as a means to transfer credentials. Browser based clients will automatically send appropriate cookies within XHR requests, eliminating the need of an additional authorization header.
    Another important reason is that you don’t need to do anything regarding subdomain configuration or management problems where custom headers may be stripped by some proxy servers. This can be a tedious ordeal in legacy projects.
    Using cookies can be considered an “unRESTful” practice as REST requests should be stateless. In this case we can make a compromise and pass the token value in a cookie instead of passing it via a custom header. Effectively we are using cookies as just a way to pass the token value instead of the session_id directly. This approach could be considered stateless, but we can leave it up to your preferences.
    API endpoint URLs can also be versioned. Additionally, they can include the expected response format as an extension in the path name. Although these are not critical, especially during the early stages of API development, in the long run these details can certainly pay off. Especially when you need to implement new features. By checking which version the client is expecting and providing the needed format for backwards compatibility can be the best solution.
    The API endpoint URL structure could look as follows:

    example.com/api/${version_code}/${actual_request_path}.${format}
    

    And, a real example:

    example.com/api/v1.0/records.json
    

    Routing

    After choosing a base URL for the API endpoints, the next thing we need to do is to think about our routing system. It could be integrated into an existing framework, but if that is too cumbersome, a potential workaround is to create a folder named “api” in the document root. That way the API can have completely separate logic. You can extend this approach by placing the API logic into its own files, such as this:

    You can think of “www/api/Apis/Users.php” as a separate “controller” for a particular API endpoint. It would be great to reuse implementations from the existing codebase, for example reuse models that are already implemented in the project to communicate with the database.
    Finally, make sure to point all incoming requests from “/api/*” to “/api/index.php”. This can be done by changing your web server configuration.

    API Class

    Version and Format

    You should always clearly define what versions and formats your API endpoints accept and what are the default ones. This will allow you to build new features in the future while maintaining old functionalities. API version can basically be a string but you can use numeric values for better understanding and comparability. It is good to have spare digits for minor versions because it would clearly indicate that only few things are different:

    • v1.0 would mean first version.
    • v1.1 first version with some minor changes.
    • v2.0 would be a completely new version.

    Format can be anything your client needs including but not limited to JSON, XML, and even CSV. By providing it via URL as a file extension, the API endpoint url ensures readability and it becomes a no-brainer for the API consumer to know what format they can expect:

    • “/api/v1.0/records.json” would return JSON array of records
    • “/api/v1.0/records.xml” would return XML file of records

    It’s worth pointing out that you will also need to send proper a Content-Type header in the response for each of these formats.
    Upon receiving an incoming request, one of the first things you should do is check whether the API server supports the requested version and format. In your main method, which handles the incoming request, parse $_SERVER[‘PATH_INFO’] or $_SERVER[‘REQUEST_URI’] to determine if the requested format and version are supported. Then, either continue or return a 4xx response (e.g. 406 “Not Acceptable”). The most critical part in here is to always return something that the client expects. An alternative to this would be to check request header “Accept” instead of the URL path extension.

    Allowed Routes

    You could forward everything transparently to your API controllers but it might be better to use a whitelisted set of allowed routes. This would reduce flexibility a bit but will provide very clear insight of what the API endpoint URLs look like the next time you return to the code.

    private $public_routes = array(
    	'system' => array(
    		'regex' => 'system',
    	),
    	'records' => array(
    		'regex' => 'records(?:/?([0-9]+)?)',
    	),
    );
    

    You could also move these to separate files to make things cleaner. The configuration above will be used to enable requests to these URLs:

    /api/v1.0/system.json
    /api/v1.0/records.json
    /api/v1.0/records/7.json
    

    Handling PUT Data

    PHP automatically handles incoming POST data and places it under $_POST superglobal. However, that is not the case with PUT requests. All the data is “buried” into php://input. Do not forget to parse it into a separate structure or array before invoking the actual API method. A simple parse_str could be enough, but if the client is sending multipart request additional parsing may be needed to handle form boundaries. Typical use case of multipart requests include file uploads. Detecting and handling multipart requests can be done as follows:

    self::$input = file_get_contents('php://input');
    // For PUT/DELETE there is input data instead of request variables
    if (!empty(self::$input)) {
    	preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches);
    	if (isset($matches[1]) && strpos(self::$input, $matches[1]) !== false) {
    		$this->parse_raw_request(self::$input, self::$input_data);
    	} else {
    		parse_str(self::$input, self::$input_data);
    	}
    }
    

    Here, parse_raw_request could be implemented as:

    /**
     * Helper method to parse raw requests
     */
    private function parse_raw_request($input, &$a_data)
    {
    	// grab multipart boundary from content type header
    	preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches);
    	$boundary = $matches[1];
    	// split content by boundary and get rid of last -- element
    	$a_blocks = preg_split("/-+$boundary/", $input);
    	array_pop($a_blocks);
    	// loop data blocks
    	foreach ($a_blocks as $id => $block) {
    		if (empty($block)) {
    			continue;
    		}
    		// parse uploaded files
    		if (strpos($block, 'application/octet-stream') !== false) {
    			// match "name", then everything after "stream" (optional) except for prepending newlines
    			preg_match("/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s", $block, $matches);
    			// parse all other fields
    		} else {
    			// match "name" and optional value in between newline sequences
    			preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
    		}
    		$a_data[$matches[1]] = $matches[2];
    	}
    }
    

    With this, we can have the necessary request payload at Api::$input as raw input and Api::$input_data as an associative array.

    Faking PUT/DELETE

    Sometimes you can see yourself in a situation where the server does not support anything besides standard GET/POST HTTP methods. A common solution to this problem is to “fake” PUT/DELETE or any other custom request method. For that you can use a “magic” parameter, such as “_method”. If you see it in your $_REQUEST array, simply assume that the request is of specified type. Modern frameworks like Laravel have such functionality built into them. It provides great compatibility in case your server or client has limitations (for example a person is using his job’s Wi-Fi network behind corporate proxy that does not allow PUT requests.)

    Forwarding to Specific API

    If you don’t have the luxury of reusing existing project autoloaders, you can create your own with the help of spl_autoload_register function. Define it in your “api/index.php” page and call your API class located in “api/Api.php”. The API class acts as a middleware and calls the actual method. For example, a request to “/api/v1.0/records/7.json” should end up invoking “Apis/Records.php” GET method with parameter 7. This would ensure separation of concerns and provide a way to keep the logic cleaner. Of course, if it is possible to integrate this deeper into the framework you are using and reuse its specific controllers or routes you should consider that possibility too.
    Example “api/index.php” with primitive autoloader:

    <?php
    // Let's define very primitive autoloader
    spl_autoload_register(function($classname){
        $classname = str_replace('Api_', 'Apis/', $classname);
        if (file_exists(__DIR__.'/'.$classname.'.php')) {
            require __DIR__.'/'.$classname.'.php';
        }
    });
    // Our main method to handle request
    Api::serve();
    

    This will load our Api class and start serving it independently of the main project.

    OPTIONS Requests

    When a client uses custom header to forward its unique token, the browser first needs to check whenever the server supports that header. That’s where OPTIONS request come in. Its purpose is to ensure that everything is alright and safe for both the client and API server. So OPTIONS request could be firing every time a client tries to do anything. However, when a client is using cookies for credentials it saves the browser from having to send this additional OPTIONS request.

    If a client is requesting for POST /users/8.json with cookies, its request will be pretty standard:

    • App performs a POST request to /users/8.json.
    • The browser carries out the request and receives a response.

    But with custom authorization or token header:

    • App performs a POST request to /users/8.json.
    • The browser stops processing the request and initiates an OPTIONS request instead.
    • OPTIONS request is sent to /users/8.json.
    • The browser receives response with a list of all available methods and headers, as defined by the API.
    • Browser continues with the original POST request only if the custom header is present in the list of available headers.

    However, keep in mind that even when using cookies, with PUT/DELETE you might still receive that additional OPTIONS request. So be prepared to respond to it.

    Records API

    Basic Structure

    Our example Records API is pretty straightforward. It will contain all the request methods and return output back to the same main API class. For example:

    <?php
    class Api_Records
    {
    	public function __construct()
    	{
    		// In here you could initialize some shared logic between this API and rest of the project
    	}
    	/**
    	 * Get individual record or records list
    	 */
    	public function get($id = null)
    	{
    		if ($id) {
    			return $this->getRecord(intval($id));
    		} else {
    			return $this->getRecords();
    		}
    	}
    	/**
    	 * Update record
    	 */
    	public function put($record_id = null)
    	{
    		// In real world there would be call to model with validation and probably token checking
    		// Use Api::$input_data to update
    		return Api::responseOk('OK', array());
    	}
    	// ...
    

    So defining each HTTP method will allow us to build API in REST style more easily.

    Formatting Output

    Naively responding with everything received from the database back to the client can have catastrophic consequences. In order to avoid any accidental exposure of data, create specific format method which would return only whitelisted keys.
    Another benefit of whitelisted keys is that you can write documentation based on these and do all type-checkings ensuring, for example, that user_id will always be an integer, flag is_banned will always be boolean true or false, and date times will have one standard response format.

    Outputting Results

    Headers

    Separate methods for headers output will ensure that everything sent to the browser is correct. This method can use the benefits of making the API accessible via same domain while still maintaining possibility to receive custom authorization header. The choice between the same or 3rd party domain can happen with the help of HTTP_ORIGIN and HTTP_REFERER server headers. If the app is detecting that client is using x-authorization (or any other custom header) it should allow access from all origins, allow the custom header. So it could look like this:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Expose-Headers: x-authorization');
    header('Access-Control-Allow-Headers: origin, content-type, accept, x-authorization');
    header('X-Authorization: '.YOUR_TOKEN_HERE);
    

    However if the client is using cookie-based credentials, headers could be a bit different, allowing only requested host and cookie related headers for credentials:

    header('Access-Control-Allow-Origin: '.$origin);
    header('Access-Control-Expose-Headers: set-cookie, cookie');
    header('Access-Control-Allow-Headers: origin, content-type, accept, set-cookie, cookie');
    // Allow cookie credentials because we're on the same domain
    header('Access-Control-Allow-Credentials: true');
    if (strtolower($_SERVER['REQUEST_METHOD']) != 'options') {
    	setcookie(TOKEN_COOKIE_NAME, YOUR_TOKEN_HERE, time()+86400*30, '/', '.'.$_SERVER['HTTP_HOST']);
    }
    

    Keep in mind that OPTIONS request does not support cookies so app will not send them with it. And, finally this allows all our wanted HTTP methods to have expiration of access control:

    header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
    header('Access-Control-Max-Age: 86400');
    

    Body

    The body itself should contain the response in a format requested by your client with a 2xx HTTP status upon success, 4xx status upon failure due to client and 5xx status upon failure due to server. Structure of the response can vary, although specifying “status” and “response” fields could be beneficial too. For example, if the client is trying to register a new user and the username is already taken it you could send a response with HTTP status 200 but a JSON in the body that looks something like:

    {“status”: “ERROR”, “response”: ”username already taken”}
    

    … instead of HTTP 4xx error directly.

    Conclusion

    No two projects are exactly the same. The strategy outlined in this article may or may not be be a good fit for your case, but the core concepts should be similar nonetheless. It’s worth noting that not every page can have the latest trending or up-to-date framework behind it, and sometimes the anger regarding “why my REST Symfony bundle doesn’t work here” can be turned into a motivation for building something useful, something that works. The end result may not be as shiny, as it will always be some custom and project-specific implementation, but at the end of the day the solution will be something that really works; and in a scenario like this that should be the goal of every API developer.
    Example implementations of the concepts discussed here has been uploaded to a GitHub repository for convenience. You may not want to use these sample codes directly in production as they are, but this could easily work as a starting point for your next legacy PHP API integration project.
    Had to implement a REST API server for some legacy project recently? Share your experience with us in the comment section below.

  • Before Debugging PHP That’s Not Working, Consult This List of the 10 Most Common Mistakes That PHP Developers Make

    PHP makes it relatively easy to build a web-based system, which is much of the reason for its popularity. But its ease of use notwithstanding, PHP has evolved into quite a sophisticated language with many frameworks, nuances, and subtleties that can bite developers, leading to hours of hair-pulling debugging. This article highlights ten of the more common mistakes that PHP developers need to beware of.
    This PHP logo broke thanks to one of the 10 most common PHP mistakes

    Common Mistake #1: Leaving dangling array references after foreach loops

    Not sure how to use foreach loops in PHP? Using references in foreach loops can be useful if you want to operate on each element in the array that you are iterating over. For example:

    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
        $value = $value * 2;
    }
    // $arr is now array(2, 4, 6, 8)
    

    The problem is that, if you’re not careful, this can also have some undesirable side effects and consequences. Specifically, in the above example, after the code is executed, $value will remain in scope and will hold a reference to the last element in the array. Subsequent operations involving $value could therefore unintentionally end up modifying the last element in the array.
    The main thing to remember is that foreach does not create a scope. Thus, $value in the above example is a reference within the top scope of the script. On each iteration foreach sets the reference to point to the next element of $array. After the loop completes, therefore, $value still points to the last element of $array and remains in scope.
    Here’s an example of the kind of evasive and confusing bugs that this can lead to:

    $array = [1, 2, 3];
    echo implode(',', $array), "\n";
    foreach ($array as &$value) {}    // by reference
    echo implode(',', $array), "\n";
    foreach ($array as $value) {}     // by value (i.e., copy)
    echo implode(',', $array), "\n";
    

    The above code will output the following:

    1,2,3
    1,2,3
    1,2,2
    

    No, that’s not a typo. The last value on the last line is indeed a 2, not a 3.
    Why?
    After going through the first foreach loop, $array remains unchanged but, as explained above, $value is left as a dangling reference to the last element in $array (since that foreach loop accessed $value by reference).
    As a result, when we go through the second foreach loop, “weird stuff” appears to happen. Specifically, since $value is now being accessed by value (i.e., by copy), foreach copies each sequential $arrayelement into $value in each step of the loop. As a result, here’s what happens during each step of the second foreach loop:

    • Pass 1: Copies $array[0] (i.e., “1”) into $value (which is a reference to $array[2]), so $array[2] now equals 1. So $array now contains [1, 2, 1].
    • Pass 2: Copies $array[1] (i.e., “2”) into $value (which is a reference to $array[2]), so $array[2] now equals 2. So $array now contains [1, 2, 2].
    • Pass 3: Copies $array[2] (which now equals “2”) into $value (which is a reference to $array[2]), so $array[2] still equals 2. So $array now contains [1, 2, 2].

    To still get the benefit of using references in foreach loops without running the risk of these kinds of problems, call unset() on the variable, immediately after the foreach loop, to remove the reference; e.g.:

    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
        $value = $value * 2;
    }
    unset($value);   // $value no longer references $arr[3]
    

    Common Mistake #2: Misunderstanding isset() behavior

    Despite its name, isset() not only returns false if an item does not exist, but also returns false for nullvalues.
    This behavior is more problematic than it might appear at first and is a common source of problems.
    Consider the following:

    $data = fetchRecordFromStorage($storage, $identifier);
    if (!isset($data['keyShouldBeSet']) {
        // do something here if 'keyShouldBeSet' is not set
    }
    

    The author of this code presumably wanted to check if keyShouldBeSet was set in $data. But, as discussed, isset($data['keyShouldBeSet']) will also return false if $data['keyShouldBeSet'] was set, but was set to null. So the above logic is flawed.
    Here’s another example:

    if ($_POST['active']) {
        $postData = extractSomething($_POST);
    }
    // ...
    if (!isset($postData)) {
        echo 'post not active';
    }
    

    The above code assumes that if $_POST['active'] returns true, then postData will necessarily be set, and therefore isset($postData) will return true. So conversely, the above code assumes that the only way that isset($postData) will return false is if $_POST['active'] returned false as well.
    Not.
    As explained, isset($postData) will also return false if $postData was set to null. It therefore is possible for isset($postData) to return false even if $_POST['active'] returned true. So again, the above logic is flawed.
    And by the way, as a side point, if the intent in the above code really was to again check if $_POST['active']returned true, relying on isset() for this was a poor coding decision in any case. Instead, it would have been better to just recheck $_POST['active']; i.e.:

    if ($_POST['active']) {
        $postData = extractSomething($_POST);
    }
    // ...
    if ($_POST['active']) {
        echo 'post not active';
    }
    

    For cases, though, where it is important to check if a variable was really set (i.e., to distinguish between a variable that wasn’t set and a variable that was set to null), the array_key_exists() method is a much more robust solution.
    For example, we could rewrite the first of the above two examples as follows:

    $data = fetchRecordFromStorage($storage, $identifier);
    if (! array_key_exists('keyShouldBeSet', $data)) {
        // do this if 'keyShouldBeSet' isn't set
    }
    

    Moreover, by combining array_key_exists() with get_defined_vars(), we can reliably check whether a variable within the current scope has been set or not:

    if (array_key_exists('varShouldBeSet', get_defined_vars())) {
        // variable $varShouldBeSet exists in current scope
    }
    

    Common Mistake #3: Confusion about returning by reference vs. by value

    Consider this code snippet:

    class Config
    {
        private $values = [];
        public function getValues() {
            return $this->values;
        }
    }
    $config = new Config();
    $config->getValues()['test'] = 'test';
    echo $config->getValues()['test'];
    

    If you run the above code, you’ll get the following:

    PHP Notice:  Undefined index: test in /path/to/my/script.php on line 21
    

    What’s wrong?
    The issue is that the above code confuses returning arrays by reference with returning arrays by value. Unless you explicitly tell PHP to return an array by reference (i.e., by using&), PHP will by default return the the array “by value”. This means that a copy of the array will be returned and therefore the called function and the caller will not be accessing the same instance of the array.
    So the above call to getValues() returns a copy of the $values array rather than a reference to it. With that in mind, let’s revisit the two key lines from the above the example:

    // getValues() returns a COPY of the $values array, so this adds a 'test' element
    // to a COPY of the $values array, but not to the $values array itself.
    $config->getValues()['test'] = 'test';
    // getValues() again returns ANOTHER COPY of the $values array, and THIS copy doesn't
    // contain a 'test' element (which is why we get the "undefined index" message).
    echo $config->getValues()['test'];
    

    One possible fix would be to save the first copy of the $values array returned by getValues() and then operate on that copy subsequently; e.g.:

    $vals = $config->getValues();
    $vals['test'] = 'test';
    echo $vals['test'];
    

    That code will work fine (i.e., it will output test without generating any “undefined index” message), but depending on what you’re trying to accomplish, this approach may or may not be adequate. In particular, the above code will not modify the original $values array. So if you do want your modifications (such as adding a ‘test’ element) to affect the original array, you would instead need to modify the getValues() function to return a reference to the $values array itself. This is done by adding a & before the function name, thereby indicating that it should return a reference; i.e.:

    class Config
    {
        private $values = [];
        // return a REFERENCE to the actual $values array
        public function &getValues() {
            return $this->values;
        }
    }
    $config = new Config();
    $config->getValues()['test'] = 'test';
    echo $config->getValues()['test'];
    

    The output of this will be test, as expected.
    But to make things more confusing, consider instead the following code snippet:

    class Config
    {
        private $values;
        // using ArrayObject rather than array
        public function __construct() {
            $this->values = new ArrayObject();
        }
        public function getValues() {
            return $this->values;
        }
    }
    $config = new Config();
    $config->getValues()['test'] = 'test';
    echo $config->getValues()['test'];
    

    If you guessed that this would result in the same “undefined index” error as our earlier array example, you were wrong. In fact, this code will work just fine. The reason is that, unlike arrays, PHP always passes objects by reference. (ArrayObject is an SPL object, which fully mimics arrays usage, but works as an object.)
    As these examples demonstrate, it is not always entirely obvious in PHP whether you are dealing with a copy or a reference. It is therefore essential to understand these default behaviors (i.e., variables and arrays are passed by value; objects are passed by reference) and also to carefully check the API documentation for the function you are calling to see if it is returning a value, a copy of an array, a reference to an array, or a reference to an object.
    All that said, it is important to note that the practice of returning a reference to an array or an ArrayObject is generally something that should be avoided, as it provides the caller with the ability to modify the instance’s private data. This “flies in the face” of encapsulation. Instead, it’s better to use old style “getters” and “setters”, e.g.:

    class Config
    {
        private $values = [];
        public function setValue($key, $value) {
            $this->values[$key] = $value;
        }
        public function getValue($key) {
            return $this->values[$key];
        }
    }
    $config = new Config();
    $config->setValue('testKey', 'testValue');
    echo $config->getValue('testKey');    // echos 'testValue'
    

    This approach gives the caller the ability to set or get any value in the array without providing public access to the otherwise-private $values array itself.

    Common Mistake #4: Performing queries in a loop

    It’s not uncommon to come across something like this if your PHP is not working:

    $models = [];
    foreach ($inputValues as $inputValue) {
        $models[] = $valueRepository->findByValue($inputValue);
    }
    

    While there may be absolutely nothing wrong here, but if you follow the logic in the code, you may find that the innocent looking call above to $valueRepository->findByValue() ultimately results in a query of some sort, such as:

    $result = $connection->query("SELECT `x`,`y` FROM `values` WHERE `value`=" . $inputValue);
    

    As a result, each iteration of the above loop would result in a separate query to the database. So if, for example, you supplied an array of 1,000 values to the loop, it would generate 1,000 separate queries to the resource! If such a script is called in multiple threads, it could potentially bring the system to a grinding halt.
    It’s therefore crucial to recognize when queries are being made by your code and, whenever possible, gather the values and then run one query to fetch all the results.
    One example of a fairly common place to encounter querying being done inefficiently (i.e., in a loop) is when a form is posted with a list of values (IDs, for example). Then, to retrieve the full record data for each of the IDs, the code will loop through the array and do a separate SQL query for each ID. This will often look something like this:

    $data = [];
    foreach ($ids as $id) {
        $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` = " . $id);
        $data[] = $result->fetch_row();
    }
    

    But the same thing can be accomplished much more efficiently in a single SQL query as follows:

    $data = [];
    if (count($ids)) {
        $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` IN (" . implode(',', $ids));
        while ($row = $result->fetch_row()) {
            $data[] = $row;
        }
    }
    

    It’s therefore crucial to recognize when queries are being made, either directly or indirectly, by your code. Whenever possible, gather the values and then run one query to fetch all the results. Yet caution must be exercised there as well, which leads us to our next common PHP mistake…

    Common Mistake #5: Memory usage headfakes and inefficiencies

    While fetching many records at once is definitely more efficient than running a single query for each row to fetch, such an approach can potentially lead to an “out of memory” condition in libmysqlclient when using PHP’s mysql extension.
    To demonstrate, let’s take a look at a test box with limited resources (512MB RAM), MySQL, and php-cli.
    We’ll bootstrap a database table like this:

    // connect to mysql
    $connection = new mysqli('localhost', 'username', 'password', 'database');
    // create table of 400 columns
    $query = 'CREATE TABLE `test`(`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT';
    for ($col = 0; $col < 400; $col++) {
        $query .= ", `col$col` CHAR(10) NOT NULL";
    }
    $query .= ');';
    $connection->query($query);
    // write 2 million rows
    for ($row = 0; $row < 2000000; $row++) {
        $query = "INSERT INTO `test` VALUES ($row";
        for ($col = 0; $col < 400; $col++) {
            $query .= ', ' . mt_rand(1000000000, 9999999999);
        }
        $query .= ')';
        $connection->query($query);
    }
    

    OK, now let’s check resources usage:

    // connect to mysql
    $connection = new mysqli('localhost', 'username', 'password', 'database');
    echo "Before: " . memory_get_peak_usage() . "\n";
    $res = $connection->query('SELECT `x`,`y` FROM `test` LIMIT 1');
    echo "Limit 1: " . memory_get_peak_usage() . "\n";
    $res = $connection->query('SELECT `x`,`y` FROM `test` LIMIT 10000');
    echo "Limit 10000: " . memory_get_peak_usage() . "\n";
    

    Output:

    Before: 224704
    Limit 1: 224704
    Limit 10000: 224704
    

    Cool. Looks like the query is safely managed internally in terms of resources.
    Just to be sure, though, let’s boost the limit one more time and set it to 100,000. Uh-oh. When we do that, we get:

    PHP Warning:  mysqli::query(): (HY000/2013):
                  Lost connection to MySQL server during query in /root/test.php on line 11
    

    What happened?
    The issue here is the way PHP’s mysql module works. It’s really just a proxy for libmysqlclient, which does the dirty work. When a portion of data is selected, it goes directly into memory.  Since this memory is not managed by PHP’s manager, memory_get_peak_usage() won’t show any increase in resources utilization as we up the limit in our query. This leads to problems like the one demonstrated above where we’re tricked into complacency thinking that our memory management is fine. But in reality, our memory management is seriously flawed and we can experience problems like the one shown above.
    You can at least avoid the above headfake (although it won’t itself improve your memory utilization) by instead using the mysqlnd module.  mysqlnd is compiled as a native PHP extension and it does use PHP’s memory manager.
    Therefore, if we run the above test using mysqlnd rather than mysql, we get a much more realistic picture of our memory utilization:

    Before: 232048
    Limit 1: 324952
    Limit 10000: 32572912
    

    And it’s even worse than that, by the way. According to PHP documentation, mysql uses twice as many resources as mysqlnd to store data, so the original script using mysql really used even more memory than shown here (roughly twice as much).
    To avoid such problems, consider limiting the size of your queries and using a loop with small number of iterations; e.g.:

    $totalNumberToFetch = 10000;
    $portionSize = 100;
    for ($i = 0; $i <= ceil($totalNumberToFetch / $portionSize); $i++) {
        $limitFrom = $portionSize * $i;
        $res = $connection->query(
                             "SELECT `x`,`y` FROM `test` LIMIT $limitFrom, $portionSize");
    }
    

    When we consider both this PHP mistake and mistake #4 above, we realize that there is a healthy balance that your code ideally needs to achieve between, on the one hand, having your queries being too granular and repetitive, vs. having each of your individual queries be too large. As is true with most things in life, balance is needed; either extreme is not good and can cause problems with PHP not working properly.

    Common Mistake #6: Ignoring Unicode/UTF-8 issues

    In some sense, this is really more of an issue in PHP itself than something you would run into while debugging PHP, but it has never been adequately addressed. PHP 6’s core was to be made Unicode-aware, but that was put on hold when development of PHP 6 was suspended back in 2010.
    But that by no means absolves the developer from properly handing UTF-8 and avoiding the erroneous assumption that all strings will necessarily be “plain old ASCII”. Code that fails to properly handle non-ASCII strings is notorious for introducing gnarly heisenbugs into your code. Even simple strlen($_POST['name'])calls could cause problems if someone with a last name like “Schrödinger” tried to sign up into your system.
    Here’s a small checklist to avoid such problems in your code:

    • If you don’t know much about Unicode and UTF-8, you should at least learn the basics. There’s a great primer here.
    • Be sure to always use the mb_* functions instead of the old string functions (make sure the “multibyte” extension is included in your PHP build).
    • Make sure your database and tables are set to use Unicode (many builds of MySQL still use latin1 by default).
    • Remember that json_encode() converts non-ASCII symbols (e.g., “Schrödinger” becomes “Schr\u00f6dinger”) but serialize() does not.
    • Make sure your PHP code files are also UTF-8 encoded to avoid collisions when concatenating strings with hardcoded or configured string constants.

    A particularly valuable resource in this regard is the UTF-8 Primer for PHP and MySQL post by Francisco Claria on this blog.

    Common Mistake #7: Assuming $_POST will always contain your POST data

    Despite its name, the $_POST array won’t always contain your POST data and can be easily found empty. To understand this, let’s take a look at an example. Assume we make a server request with a jQuery.ajax() call as follows:

    // js
    $.ajax({
        url: 'https://my.site/some/path',
        method: 'post',
        data: JSON.stringify({a: 'a', b: 'b'}),
        contentType: 'application/json'
    });
    

    (Incidentally, note the contentType: 'application/json' here. We send data as JSON, which is quite popular for APIs. It’s the default, for example, for posting in the AngularJS $http service.)
    On the server side of our example, we simply dump the $_POST array:

    // php
    var_dump($_POST);
    

    Surprisingly, the result will be:

    array(0) { }
    

    Why? What happened to our JSON string {a: 'a', b: 'b'}?
    The answer is that PHP only parses a POST payload automatically when it has a content type of application/x-www-form-urlencoded or multipart/form-data. The reasons for this are historical — these two content types were essentially the only ones used years ago when PHP’s $_POST was implemented. So with any other content type (even those that are quite popular today, like application/json), PHP doesn’t automatically load the POST payload.
    Since $_POST is a superglobal, if we override it once (preferably early in our script), the modified value (i.e., including the POST payload) will then be referenceable throughout our code. This is important since $_POSTis commonly used by PHP frameworks and almost all custom scripts to extract and transform request data.
    So, for example, when processing a POST payload with a content type of application/json, we need to manually parse the request contents (i.e., decode the JSON data) and override the $_POST variable, as follows:

    // php
    $_POST = json_decode(file_get_contents('php://input'), true);
    

    Then when we dump the $_POST array, we see that it correctly includes the POST payload; e.g.:

    array(2) { ["a"]=> string(1) "a" ["b"]=> string(1) "b" }
    

    Common Mistake #8: Thinking that PHP supports a character data type

    Look at this sample piece of code and try guessing what it will print:

    for ($c = 'a'; $c <= 'z'; $c++) {
        echo $c . "\n";
    }
    

    If you answered ‘a’ through ‘z’, you may be surprised to know that you were wrong.
    Yes, it will print ‘a’ through ‘z’, but then it will also print ‘aa’ through ‘yz’. Let’s see why.
    In PHP there’s no char datatype; only string is available. With that in mind, incrementing the string z in PHP yields aa:

    php> $c = 'z'; echo ++$c . "\n";
    aa
    

    Yet to further confuse matters, aa is lexicographically less than z:

    php> var_export((boolean)('aa' < 'z')) . "\n";
    true
    

    That’s why the sample code presented above prints the letters a through z, but then also prints aathrough yz. It stops when it reachs za, which is the first value it encounters that it “greater than” z:

    php> var_export((boolean)('za' < 'z')) . "\n";
    false
    

    That being the case, here’s one way to properly loop through the values ‘a’ through ‘z’ in PHP:

    for ($i = ord('a'); $i <= ord('z'); $i++) {
        echo chr($i) . "\n";
    }
    

    Or alternatively:

    $letters = range('a', 'z');
    for ($i = 0; $i < count($letters); $i++) {
        echo $letters[$i] . "\n";
    }
    

    Common Mistake #9: Ignoring coding standards

    Although ignoring coding standards doesn’t directly lead to needing to debug PHP code, it is still probably one of the most important things to discuss here.
    Ignoring coding standards can cause a whole slew of problems on a project. At best, it results in code that is inconsistent (since every developer is “doing their own thing”). But at worst, it produces PHP code that does not work or can be difficult (sometimes almost impossible) to navigate, making it extremely difficult to debug, enhance, maintain. And that means reduced productivity for your team, including lots of wasted (or at least unnecessary) effort.
    Fortunately for PHP developers, there is the PHP Standards Recommendation (PSR), comprised of the following five standards:

    • PSR-0: Autoloading Standard
    • PSR-1: Basic Coding Standard
    • PSR-2: Coding Style Guide
    • PSR-3: Logger Interface
    • PSR-4: Autoloader

    PSR was originally created based on inputs from maintainers of the most recognized platforms on the market. Zend, Drupal, Symfony, Joomla and others contributed to these standards, and are now following them. Even PEAR, which attempted to be a standard for years before that, participates in PSR now.
    In some sense, it almost doesn’t matter what your coding standard is, as long as you agree on a standard and stick to it, but following the PSR is generally a good idea unless you have some compelling reason on your project to do otherwise. More and more teams and projects are conforming with the PSR. Tt’s definitely recognized at this point as “the” standard by the majority of PHP developers, so using it will help ensure that new developers are familiar and comfortable with your coding standard when they join your team.

    Common Mistake #10: Misusing empty()

    Some PHP developers like using empty() for boolean checks for just about everything. There are case, though, where this can lead to confusion.
    First, let’s come back to arrays and ArrayObject instances (which mimic arrays). Given their similarity, it’s easy to assume that arrays and ArrayObject instances will behave identically. This proves, however, to be a dangerous assumption. For example, in PHP 5.0:

    // PHP 5.0 or later:
    $array = [];
    var_dump(empty($array));        // outputs bool(true) 
    $array = new ArrayObject();
    var_dump(empty($array));        // outputs bool(false)
    // why don't these both produce the same output?
    

    And to make matters even worse, the results would have been different prior to PHP 5.0:

    // Prior to PHP 5.0:
    $array = [];
    var_dump(empty($array));        // outputs bool(false) 
    $array = new ArrayObject();
    var_dump(empty($array));        // outputs bool(false)
    

    This approach is unfortunately quite popular. For example, this is the way Zend\Db\TableGateway of Zend Framework 2 returns data when calling current() on TableGateway::select() result as the doc suggests. Developer can easily become victim of this mistake with such data.
    To avoid these issues, the better approach to checking for empty array structures is to use count():

    // Note that this work in ALL versions of PHP (both pre and post 5.0):
    $array = [];
    var_dump(count($array));        // outputs int(0)
    $array = new ArrayObject();
    var_dump(count($array));        // outputs int(0)
    

    And incidentally, since PHP casts 0 to false, count() can also be used within if () conditions to check for empty arrays. It’s also worth noting that, in PHP, count() is constant complexity (O(1) operation) on arrays, which makes it even clearer that it’s the right choice.
    Another example when empty() can be dangerous is when combining it with the magic class function __get(). Let’s define two classes and have a test property in both.
    First let’s define a Regular class that includes test as a normal property:

    class Regular
    {
    	public $test = 'value';
    }
    

    Then let’s define a Magic class that uses the magic __get() operator to access its test property:

    class Magic
    {
    	private $values = ['test' => 'value'];
    	public function __get($key)
    	{
    		if (isset($this->values[$key])) {
    			return $this->values[$key];
    		}
    	}
    }
    

    OK, now let’s see what happens when we attempt to access the test property of each of these classes:

    $regular = new Regular();
    var_dump($regular->test);    // outputs string(4) "value"
    $magic = new Magic();
    var_dump($magic->test);      // outputs string(4) "value"
    

    Fine so far.
    But now let’s see what happens when we call empty() on each of these:

    var_dump(empty($regular->test));    // outputs bool(false)
    var_dump(empty($magic->test));      // outputs bool(true)
    

    Ugh. So if we rely on empty(), we can be misled into believing that the test property of $magic is empty, whereas in reality it is set to 'value'.
    Unfortunately, if a class uses the magic __get() function to retrieve a property’s value, there’s no foolproof way to check if that property value is empty or not. Outside of the class’ scope, you can really only check if a null value will be returned, and that doesn’t necessarily mean that the corresponding key is not set, since it actually could have been set to null.
    In contrast, if we attempt to reference a non-existent property of a Regular class instance, we will get a notice similar to the following:

    Notice: Undefined property: Regular::$nonExistantTest in /path/to/test.php on line 10
    Call Stack:
        0.0012     234704   1. {main}() /path/to/test.php:0
    

    So the main point here is that the empty() method should be used with care as it can lend itself to confusing – or even potentially misleading – results, if one is not careful.

    Wrap-up

    PHP’s ease of use can lull developers into a false sense of comfort, leaving themselves vulnerable to lengthy PHP debugging due to some of the nuances and idiosyncrasies of the language. This can result in PHP not working and problems such as those described herein.
    The PHP language has evolved significantly over the course of its 20 year history. Familiarizing oneself with its subtleties is a worthwhile endeavor, as it will help ensure that the software you produce is more scalable, robust, and maintainable.

  • PHP Best Practices and Tips

    Manage Your Dependencies in PHP with Composer

    What Is a Dependency?

    PHP is a great language to create web projects. One of the things you will see when using PHP is that there is a library for almost anything you need.
    A dependency in your project is a library or package that your code uses for performing tasks. For example, if you need to call a REST API you can use the curl library of PHP, or better yet, use the Guzzle library, that have all the things you need for creating the calls.

    The Problem with Dependency Management

    One common problem of using third party code is keeping it updated while time goes on. Also, there are libraries that depend on other libraries, that depends on other libraries, and so on. That is really a bad situation in a dynamic context as web development is. Not to mention which version of the library you’ll use, as sometimes you need a different version according to the context you’re in, for example, the PHP version your server has.
    And there is another catch. Requiring libraries is a big pain, you have to write all the includes into the file that needs to use a given library. When removing that class, you have to clean all the includes and delete the library. And as we all know, that can almost never happen, and we end up with a big folder of deprecated libraries, and then we need to waste our time (or the time of your team) to clean all that mess.

    Meet Composer, Your New Friend

    Composer is here to solve all those problems for us. When I first started using Composer, I thought it was a package manager, like Yum or Apt. However as they state in their documentation, they are a dependency management and not a package manager, because the packages are not installed globally. Instead, the packages are installed under a vendor folder inside your project.

    How to Manage Dependencies

    I won’t go over every detail. You can find a step by step guide explained in their getting started page, but I’ll explain quickly what you need.
    First you need to install Composer. I recommend to install it globally, and set it up so you have the Composer command available. Once you do that you have to create a composer.json file in the root of your project.
    If you want to add a new library to your project, all you have to do is add it to that file with the version you need, which looks something like this:

    {
        "require": {
            "vendor/package": "1.3.2",
            "vendor/package2": "1.*",
            "vendor/package3": "^2.0.3"
        }
    }
    

    Once you do that, next you have to run in the command line composer install and Composer will install all the needed libraries inside the vendor/ folder of your project. If you run composer update, Composer will check for new versions of the libraries and update them accordingly.
    Also, Composer will install the dependencies of these libraries without any needed extra work from you.
    There are a lot of commands you can use with Composer, run composer --help to list them all.

    Autoload Classes

    If you are already falling in love with Composer for this, you’ll definitely love it for what comes next.
    Composer offers an autoload for your classes. All you have to do is add this line in top of your project require __DIR__ . '/vendor/autoload.php'; and then just call the constructor of your class. For example, if you’re using Guzzle, you just have to call:

    $client = new GuzzleHttp\Client();
    

    and it will work. If you don’t need it anymore, just delete the class and that’s it! Well, I lied, that’s not all but almost. Head to the next section to learn the final step.

    Deleting Libraries

    We talk about the pain that is deleting a library, because you not only have to be aware of that library but also of the dependencies of that library, and being careful enough not to delete a dependency being use by another library.
    In composer this is just as simple as deleting the dependency from the composer.json file, and run composer update. Yes, it is that simple.

    Meet Packagist, the Repository for Your Projects

    As if you already don’t have enough with all this, there is a common repository for finding libraries for your projects that can be used easily with Composer.
    Packagist is the place you go when you need a library. There you can search for libraries, and see what version you want to use, depending on your needs. Also, you can write your own packages, and include them there for others to use.
    Of course, there are other ways to include packages, like directly from Github or other sources. That is out of the scope of this article, but you can find how to do this in the documentation page of Composer.

    Versioning

    When you go to the library website, you can see several available versions. In general, you will have one that is ready for production and one that is in development.
    How the versioning numbers work? Well, they follow the semantic versioning standard, which is basically as follows:
    You have 3 numbers, separated by a dot. So for example, in your composer.json file you can add something like "guzzlehttp/guzzle": "5.3.*" for requiring the Guzzle library. The first number, in this case 5, is called the major version. This number changes when big changes are made in the library. Changing this version will probably change the name of the functions, or the classes, or anything. The second number is the minor version, that is meant to be for functionality changes or additions, but having backwards compatibility with other versions. The third number is the patch number. This number is changed each time a bug is fixed, and doesn’t change the functionality of the package.
    As you can notice, you can include the wildcard * for replacing that number. This means that when you run composer update, Composer will check for the latest number in that category (major, minor or patch) and update to the newer version. It is recommended to keep the last number with a wildcard only, and update the minor version according. However, if you really trust that library and you always want the latest version, you can of course make this a wildcard as well.
    You can also use comparator operators to include a range. For example:  "guzzlehttp/guzzle": ">=5.3,<5.4"is equivalent to "guzzlehttp/guzzle": "5.3.*", and also is equivalent to "guzzlehttp/guzzle": "~5.3" using the tilde (~) operator.
    For more about versioning, go to the documentation of Composer about versioning.

    Save Disk Space

    As a last tip, if you use Git add the vendor folder in your ignore file. Having the Composer file is enough, because once the user downloads the project, it will just have to run a composer install command to fetch all the libraries.

    Summary

    In this article we explained what dependencies are, why they are important for our projects, and the problems we have when we deal with them.
    After that, we explained how Composer address all those issues in a really smart way to keep your project dependencies organized.
    Composer is another tool for your toolbelt that will save you a lot of time and headaches.
    Tips are from Toptal Developers 

  • Getting the Most Out of Your PHP Log Files: A Practical Guide

    It could rightfully be said that logs are one of the most underestimated and underutilized tools at a freelance php developer’s disposal. Despite the wealth of information they can offer, it is not uncommon for logs to be the last place a developer looks when trying to resolve a problem.
    In truth, PHP log files should in many cases be the first place to look for clues when problems occur. Often, the information they contain could significantly reduce the amount of time spent pulling out your hair trying to track down a gnarly bug.
    But perhaps even more importantly, with a bit of creativity and forethought, your logs files can be leveraged to serve as a valuable source of usage information and analytics. Creative use of log files can help answer questions such as: What browsers are most commonly being used to visit my site? What’s the average response time from my server? What was the percentage of requests to the site root? How has usage changed since we deployed the latest updates? And much, much more.
    PHP log files
    This article provides a number of tips on how to configure your log files, as well as how to process the information that they contain, in order to maximize the benefit that they provide.

    Although this article focuses technically on logging for PHP developers, much of the information presented herein is fairly “technology agnostic” and is relevant to other languages and technology stacks as well.

    Note: This article presumes basic familiarity with the Unix shell. For those lacking this knowledge, an Appendix is provided that introduces some of the commands needed for accessing and reading log files on a Unix system.

    Our PHP Log File Example Project

    As an example project for discussion purposes in this article, we will take Symfony Standard as a working project and we’ll set it up on Debian 7 Wheezy with rsyslogd, nginx, and PHP-FPM.

    composer create-project symfony/framework-standard-edition my "2.6.*"
    

    This quickly gives us a working test project with a nice UI.

    Tips for Configuring Your Log Files

    Here are some pointers on how to configure your log files to help maximize their value.

    Error Log Confguration

    Error logs represent the most basic form of logging; i.e., capturing additional information and detail when problems occur. So, in an ideal world, you would want there to be no errors and for your error logs to be empty. But when problems do occur (as they invariably do), your error logs should be one of the first stops you make on your debugging trail.
    Error logs are typically quite easy to configure.
    For one thing, all error and crash messages can be logged in the error log in exactly the same format in which they would otherwise be presented to a user. With some simple configuration, the end user will never need to see those ugly error traces on your site, while devops will be still able to monitor the system and review these error messages in all their gory detail. Here’s how to setup this kind of logging in PHP:

    log_errors = On
    error_reporting = E_ALL
    error_log = /path/to/my/error/log
    

    Another two lines that are important to include in a log file for a live site, to preclude gory levels of error detail from being to presented to users, are:

    display_errors = Off
    display_startup_errors = Off
    

    System Log (syslog) Confguration

    There are many generally compatible implementations of the syslog daemon in the open source world including:

    • syslogd and sysklogd – most often seen on BSD family systems, CentOS, Mac OS X, and others
    • syslog-ng – default for modern Gentoo and SuSE builds
    • rsyslogd – widely used on the Debian and Fedora families of operating systems

    (Note: In this article, we’ll be using rsyslogd for our examples.)
    The basic syslog configuration is generally adequate for capturing your log messages in a system-wide log file (normally /var/log/syslog; might also be /var/log/messages or /var/log/system.log depending on the distro you’re using).
    The system log provides several log facilities, eight of which (LOG_LOCAL0 through LOG_LOCAL7) are reserved for user-deployed projects. Here, for example, is how you might setup LOG_LOCAL0 to write to 4 separate log files, based on logging level (i.e., error, warning, info, debug):

    # /etc/rsyslog.d/my.conf
    local0.err      /var/log/my/err.log
    local0.warning  /var/log/my/warning.log
    local0.info     -/var/log/my/info.log
    local0.debug    -/var/log/my/debug.log
    

    Now, whenever you write a log message to LOG_LOCAL0 facility, the error messages will go to /var/log/my/err.log, warning messages will go to /var/log/my/warning.log, and so on. Note, though, that the syslog daemon filters messages for each file based on the rule of “this level and higher”. So, in the example above, all error messages will appear in all four configured files, warning messages will appear in all but the error log, info messages will appear in the info and debug logs, and debug messages will only go to debug.log.
    One additional important note; The - signs before the info and debug level files in the above configuration file example indicate that writes to those files should be perfomed asynchronously (since these operations are non-blocking). This is typically fine (and even recommended in most situations) for info and debug logs, but it’s best to have writes to the error log (and most prpobably the warning log as well) be synchronous.
    In order to shut down a less important level of logging (e.g., on a production server), you may simply redirect related messages to /dev/null (i.e., to nowhere):

    local0.debug    /dev/null # -/var/log/my/debug.log
    

    One specific customization that is useful, especially to support some of the PHP log file parsing we’ll be discussing later in this article, is to use tab as the delimiter character in log messages. This can easily be done by adding the following file in /etc/rsyslog.d:

    # /etc/rsyslog.d/fixtab.conf
    $EscapeControlCharactersOnReceive off
    

    And finally, don’t forget to restart the syslog daemon after you make any configuration changes in order for them to take effect:

    service rsyslog restart
    

    Server Log Confguration

    Unlike application logs and error logs that you can write to, server logs are exclusively written to by the corresponding server daemons (e.g., web server, database server, etc.) on each request. The only “control” you have over these logs is to the extent that the server allows you to configure its logging functionality. Though there can be a lot to sift through in these files, they are often the only way to get a clear sense of what’s going on “under the hood” with your server.
    Let’s deploy our Symfony Standard example application on nginx environment with MySQL storage backend. Here’s the nginx host config we will be using:

    server {
        server_name my.log-sandbox;
        root /var/www/my/web;
        location / {
            # try to serve file directly, fallback to app.php
            try_files $uri /app.php$is_args$args;
        }
        # DEV
        # This rule should only be placed on your development environment
        # In production, don't include this and don't deploy app_dev.php or config.php
        location ~ ^/(app_dev|config)\.php(/|$) {
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param HTTPS off;
        }
        # PROD
        location ~ ^/app\.php(/|$) {
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param HTTPS off;
            # Prevents URIs that include the front controller. This will 404:
            # https://domain.tld/app.php/some-path
            # Remove the internal directive to allow URIs like this
            internal;
        }
        error_log /var/log/nginx/my_error.log;
        access_log /var/log/nginx/my_access.log;
    }
    

    With regard to the last two directives above: access_log represents the general requests log, while error_log is for errors, and, as with application error logs, it’s worth setting up extra monitoring to be alerted to problems so you can react quickly.
    Note: This is an intentionally oversimplified nginx config file that is provided for example purposes only. It pays almost no attention to security and performance and shouldn’t be used as-is in any “real” environment.
    This is what we get in /var/log/nginx/my_access.log after typing https://my.log-sandbox/app_dev.php/ in browser and hitting Enter.

    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /app_dev.php/ HTTP/1.1" 200 6715 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/framework/css/body.css HTTP/1.1" 200 6657 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/framework/css/structure.css HTTP/1.1" 200 1191 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/acmedemo/css/demo.css HTTP/1.1" 200 2204 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/acmedemo/images/welcome-quick-tour.gif HTTP/1.1" 200 4770 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/acmedemo/images/welcome-demo.gif HTTP/1.1" 200 4053 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/acmedemo/images/welcome-configure.gif HTTP/1.1" 200 3530 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /favicon.ico HTTP/1.1" 200 6518 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:30 +0300] "GET /app_dev.php/_wdt/e50d73 HTTP/1.1" 200 13265 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    

    This shows that, for serving one page, the browser actually performs 9 HTTP calls. 7 of those, however, are requests to static content, which are plain and lightweight. However, they still take network resources and this is what can be optimized by using various sprites and minification techniques.
    While those optimisations are to be discussed in another article, what’s relavant here is that we can log requests to static contents separately by using another location directive for them:

    location ~ \.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js)$ {
        access_log /var/log/nginx/my_access-static.log;
    }
    

    Remember that nginx location performs simple regular expression matching, so you can include as many static contents extensions as you expect to dispatch on your site.
    Parsing such logs is no different than parsing application logs.

    Other Logs Worth Mentioning

    Two other PHP logs worth mentioning are the debug log and data storage log.

    The Debug Log

    Another convenient thing about nginx logs is the debug log. We can turn it on by replacing the error_logline of the config with the following (requires that the nginx debug module be installed):

    error_log /var/log/nginx/my_error.log debug;
    

    The same setting applies for Apache or whatever other webserver you use.
    And incidentally, debug logs are not related to error logs, even though they are configured in the error_logdirective.
    Although the debug log can indeed be verbose (a single nginx request, for example, generated 127KB of log data!), it can still be very useful. Wading through a log file may be cumbersome and tedious, but it can often quickly provide clues and information that greatly help accelerate the debugging process.
    In particular, the debug log can really help with debugging nginx configurations, especially the most complicated parts, like location matching and rewrite chains.
    Of course, debug logs should never be enabled in a production environment. The amount of space they use also and the amount of information that they store means a lot of I/O load on your server, which can degrade the whole system’s performance significantly.

    Data Storage Logs

    Another type of server log (useful for debugging) is data storage logs. In MySQL, you can turn them on by adding these lines:

    [mysqld]
    general_log = 1
    general_log_file = /var/log/mysql/query.log
    

    These logs simply contain a list of queries run by the system while serving database requests in chronological order, which can be helpful for various debugging and tracing needs. However, they should not stay enabled on production systems, since they will generate extra unnecessary I/O load, which affects performance.

    Writing to Your Log Files

    PHP itself provides functions for opening, writing to, and closing log files (openlog(), syslog(), and closelog(), respectively).
    There are also numerous logging libraries for the PHP developer, such as Monolog (popular among Symfonyand Laravel users), as well as various framework-specific implementations, such as the logging capabilities incorporated into CakePHP. Generally, libraries like Monolog not only wrap syslog() calls, but also allow using other backend functionality and tools.
    Here’s a simple example of how to write to the log:

    <?php
    openlog(uniqid(), LOG_ODELAY, LOG_LOCAL0);
    syslog(LOG_INFO, 'It works!');
    

    Our call here to openlog:

    • configures PHP to prepend a unique identifier to each system log message within the script’s lifetime
    • sets it to delay opening the syslog connection until the first syslog() call has occurred
    • sets LOG_LOCAL0 as the default logging facility

    Here’s what the contents of the log file would look like after running the above code:

    # cat /var/log/my/info.log
    Mar  2 00:23:29 log-sandbox 54f39161a2e55: It works!
    

    Maximizing the Value of Your PHP Log Files

    Now that we’re all good with theory and basics, let’s see how much we can get from logs making as few changes as possible to our sample Symfony Standard project.
    First, let’s create the scripts src/log-begin.php (to properly open and configure our logs) and src/log-end.php (to log information about successful completion). Note that, for simplicity, we’ll just write all messages to the info log.

    # src/log-begin.php
    <?php
    define('START_TIME', microtime(true));
    openlog(uniqid(), LOG_ODELAY, LOG_LOCAL0);
    syslog(LOG_INFO, 'BEGIN');
    syslog(LOG_INFO, "URI\t{$_SERVER['REQUEST_URI']}");
    $browserHash = substr(md5($_SERVER['HTTP_USER_AGENT']), 0, 7);
    syslog(LOG_INFO, "CLIENT\t{$_SERVER['REMOTE_ADDR']}\t{$browserHash}"); <br />
    # src/log-end.php
    <?php
    syslog(LOG_INFO, "DISPATCH TIME\t" . round(microtime(true) - START_TIME, 2));
    syslog(LOG_INFO, 'END');
    

    And let’s require these scripts in app.php:

    <?php
    require_once(dirname(__DIR__) . '/src/log-begin.php');
    syslog(LOG_INFO, "MODE\tPROD");
    # original app.php contents
    require_once(dirname(__DIR__) . '/src/log-end.php');
    

    For the development environment, we want to require these scripts in app_dev.php as well. The code to do so would be the same as above, except we would set the MODE to DEV rather than PROD.
    We also want to track what controllers are being invoked, so let’s add one more line in Acme\DemoBundle\EventListener\ControllerListener, right at the beginning of the ControllerListener::onKernelController() method:

    syslog(LOG_INFO, "CONTROLLER\t" . get_class($event->getController()[0]));
    

    Note that these changes total a mere 15 extra lines of code, but can collectively yield a wealth of information.

    Analyzing the Data in Your Log Files

    For starters, let’s see how many HTTP requests are required to serve each page load.
    Here’s the info in the logs for one request, based on the way we’ve configured our logging:

    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: BEGIN
    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: URI    /app_dev.php/
    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: CLIENT 192.168.56.1    1b101cd
    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: MODE   DEV
    Mar  3 12:04:23 log-sandbox 54f58724b1ccc: CONTROLLER Acme\DemoBundle\Controller\WelcomeController
    Mar  3 12:04:25 log-sandbox 54f58724b1ccc: DISPATCH TIME  4.51
    Mar  3 12:04:25 log-sandbox 54f58724b1ccc: END
    Mar  3 12:04:25 log-sandbox 54f5872967dea: BEGIN
    Mar  3 12:04:25 log-sandbox 54f5872967dea: URI    /app_dev.php/_wdt/59b8b6
    Mar  3 12:04:25 log-sandbox 54f5872967dea: CLIENT 192.168.56.1    1b101cd
    Mar  3 12:04:25 log-sandbox 54f5872967dea: MODE   DEV
    Mar  3 12:04:28 log-sandbox 54f5872967dea: CONTROLLER Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController
    Mar  3 12:04:29 log-sandbox 54f5872967dea: DISPATCH TIME  4.17
    Mar  3 12:04:29 log-sandbox 54f5872967dea: END
    

    So now we know that each page load is actually served with two HTTP requests.
    Actually there are two points worth mentioning here. First, the two requests per page load is for using Symfony in dev mode (which I have done throughout this article). You can identify dev mode calls by searching for /app-dev.php/ URL chunks. Second, let’s say each page load is served with two subsequent requests to the Symfony app. As we saw earlier in the nginx access logs, there are actually more HTTP calls, some of which are for static content.
    OK, now let’s surf a bit on the demo site (to build up the data in the log files) and let’s see what else we can learn from these logs.

    How many requests were served in total since the beginning of the logfile?

    # grep -c BEGIN info.log
    10
    

    Did any of them fail (did the script shut down without reaching the end)?

    # grep -c END info.log
    10
    

    We see that the number of BEGIN and END records match, so this tells us that all of the calls were successful. (If the PHP script had not completed successfully, it would not have reached execution of the src/log-end.php script.)

    What was the percentage of requests to the site root?

    # `grep -cE "\s/app_dev.php/$" info.log`
    2
    

    This tells us that there were 2 page loads of the site root. Since we previously learned that (a) there are 2 requests to the app per page load and (b) there were a total of 10 HTTP requests, the percentage of requests to the site root was 40% (i.e., 2×2/10).

    Which controller class is responsible for serving requests to site root?

    # grep -E "\s/$|\s/app_dev.php/$" info.log | head -n1
    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: URI  /app_dev.php/
    # grep 54f58724b1ccc info.log | grep CONTROLLER
    Mar  3 12:04:23 log-sandbox 54f58724b1ccc: CONTROLLER   Acme\DemoBundle\Controller\WelcomeController
    

    Here we used the unique ID of a request to check all log messages related to that single request. We thereby were able to determine that the controller class responsible for serving requests to site root is Acme\DemoBundle\Controller\WelcomeController.

    Which clients with IPs of subnet 192.168.0.0/16 have accessed the site?

    # grep CLIENT info.log | cut -d":" -f4 | cut -f2 | sort | uniq
    192.168.56.1
    

    As expected in this simple test case, only my host computer has accessed the site. This is of course a very simplistic example, but the capability that it demonstrates (of being able to analyse the sources of the traffic to your site) is obviously quite powerful and important.

    How much of the traffic to my site has been from FireFox?

    Having 1b101cd as the hash of my Firefox User-Agent, I can answer this question as follows:

    # grep -c 1b101cd info.log
    8
    # grep -c CLIENT info.log
    10
    

    Answer: 80% (i.e., 8/10)

    What is the percentage of requests that yielded a “slow” response?

    For purposes of this example, we’ll define “slow” as taking more than 5 seconds to provide a response. Accordingly:

    # grep "DISPATCH TIME" info.log | grep -cE "\s[0-9]{2,}\.|\s[5-9]\."
    2
    

    Answer: 20% (i.e., 2/10)

    Did anyone ever supply GET parameters?

    # grep URI info.log | grep \?
    

    No, Symfony standard uses only URL slugs, so this also tells us here that no one has attempted to hack the site.
    These are just a handful of relatively rudimentary examples of the ways in which logs files can be creatively leveraged to yield valuable usage information and even basic analytics.

    Other Things to Keep in Mind

    Keeping Things Secure

    Another heads-up is for security. You might think that logging requests is a good idea, in most cases it indeed is. However, it’s important to be extremely careful about removing any potentially sensitive user information before storing it in the log.

    Fighting Log File Bloat

    Since log files are text files to which you always append information, they are constantly growing. Since this is a well-known issue, there are some fairly standard approaches to controlling log file growth.
    The easiest is to rotate the logs. Rotating logs means:

    • Periodically replacing the log with a new empty file for further writing
    • Storing the old file for history
    • Removing files that have “aged” sufficiently to free up disk space
    • Making sure the application can write to the logs uniterrupted when these file changes occur

    The most common solution for this is logrotate, which ships pre-installed with most *nix distributions. Let’s see a simple configuration file for rotating our logs:

    /var/log/my/debug.log
    /var/log/my/info.log
    /var/log/my/warning.log
    /var/log/my/error.log
    {
        rotate 7
        daily
        missingok
        notifempty
        delaycompress
        compress
        sharedscripts
        postrotate
            invoke-rc.d rsyslog rotate > /dev/null
        endscript
    }
    

    Another, more advanced approach is to make rsyslogd itself write messages into files, dynamically created based on current date and time. This would still require a custom solution for removal of older files, but lets devops manage timeframes for each log file precisely. For our example:

    $template DynaLocal0Err,        "/var/log/my/error-%$NOW%-%$HOUR%.log"
    $template DynaLocal0Info,       "/var/log/my/info-%$NOW%-%$HOUR%.log"
    $template DynaLocal0Warning,    "/var/log/my/warning-%$NOW%-%$HOUR%.log"
    $template DynaLocal0Debug,      "/var/log/my/debug-%$NOW%-%$HOUR%.log"
    local1.err      -?DynaLocal0Err
    local1.info     -?DynaLocal0Info
    local1.warning  -?DynaLocal0Warning
    local1.debug    -?DynaLocal0Debug
    

    This way, rsyslog will create an individual log file each hour, and there won’t be any need for rotating them and restarting the daemon. Here’s how log files older than 5 days can be removed to accomplish this solution:

    find /var/log/my/ -mtime +5 -print0 | xargs -0 rm
    

    Remote Logs

    As the project grows, parsing information from logs gets more and more resource hungry. This not only means creating extra server load; it also means creating peak load on the CPU and disk drives at the times when you parse logs, which can degrade server response time for users (or in a worst case can even bring the site down).
    To solve this, consider setting up a centralized logging server. All you need for this is another box with UDP port 514 (default) open. To make rsyslogd listen to connections, add the following line to its config file:

    $UDPServerRun 514
    

    Having this, setting up the client is then as easy as:

    *.*   @HOSTNAME:514
    

    (where HOSTNAME is the host name of your remote logging server).

    Conclusion

    While this article has demonstrated some of the creative ways in which log files can offer way more valuable information than you may have previously imagined, it’s important to emphasize that we’ve only scratched the surface of what’s possible. The extent, scope, and format of what you can log is almost limitless. This means that – if there’s usage or analytics data you want to extract from your logs – you simply need to log it in a way that will make it easy to subsequently parse and analyze. Moreover, that analysis can often be performed with standard Linux command line tools like grep, sed, or awk.
    Indeed, PHP log files are a most powerful tool that can be of tremendous benefit.

    Resources

    Code on GitHub: https://github.com/isanosyan/toptal-blog-logs-post-example


    Appendix: Reading and Manipulating Log Files in the Unix Shell

    Here is a brief intro to some of the more common *nix command line tools that you’ll want to be familiar with for reading and manipulating your log files.

    • cat is perhaps the most simple one. It prints the whole file to the output stream. For example, the following command will print logfile1 to the console:
      cat logfile1
      
    • > character allows user to redirect output, for example into another file. Opens target stream in write mode (which means wiping target contents). Here’s how we replace contents of tmpfile with contents of logfile1:
      cat logfile1 > tmpfile
      
    • >> redirects output and opens target stream in append mode. Current contents of target file will be preserved, new lines will be added to the bottom. This will append logfile1 contents to tmpfile:
      cat logfile1 >> tmpfile
      
    • grep filters file by some pattern and prints only matching lines. Command below will only print lines of logfile1 containing Bingo message:
      grep Bingo logfile1
      
    • cut prints contents of a single column (by number starting from 1). By default searches for tab characters as delimiters between column. For example, if you have file full of timestamps in format YYYY-MM-DD HH:MM:SS, this will allow you to print only years:
      cut -d"-" -f1 logfile1
      
    • head displays only the first lines of a file
    • tail displays only the last lines of a file
    • sort sorts lines in the output
    • uniq filters out duplicate lines
    • wc counts words (or lines when used with the -l flag)
    • | (i.e., the “pipe” symbol) supplies output from one command as input to the next. Pipe is very convenient for combining commands. For example, here’s how we can find months of 2014 that occur within a set of timestamps:
      grep -E "^2014" logfile1 | cut -d"-" -f2 | sort | uniq
      

    Here we first match lines against regular expression “starts with 2014”, then cut months. Finally, we use combination of sort and uniq to print occurrences only once.

  • Building an IMAP Email Client with PHP

    Building an IMAP Email Client with PHP

    [pt_text]Developers sometimes run into tasks that require access to email mailboxes. In most cases, this is done using the Internet Message Access Protocol, or IMAP. As a PHP developer, I first turned to PHP’s built in IMAP library, but this library is buggy and impossible to debug or modify. It is also not possible to customize IMAP commands to make full use of the protocol’s abilities.
    So today, we will create a working IMAP email client from the ground up using PHP. We will also see how to use Gmail’s special commands.
    We will implement IMAP in a custom class, imap_driver. I will explain each step while building the class. You can download the whole imap_driver.php at the end of the article.

    Establishing a Connection

    IMAP is a connection-based protocol and typically operates over TCP/IP with SSL security, so before we can make any IMAP calls we must open the connection.
    We need to know the URL and port number of the IMAP server we want to connect to. This information is usually advertised in the service’s website or documentation. For example, for Gmail, the URL is ssl://imap.gmail.com on port 993.
    Since we want to know if initialization was successful, we will leave our class constructor empty, and all the connections will be made in a custom init() method, which will return false if the connection cannot be established:

    class imap_driver
    {
        private $fp;                      // file pointer
        public $error;                    // error message
        ...
        public function init($host, $port)
        {
            if (!($this->fp = fsockopen($host, $port, $errno, $errstr, 15))) {
                $this->error = "Could not connect to host ($errno) $errstr";
                return false;
            }
            if (!stream_set_timeout($this->fp, 15)) {
                $this->error = "Could not set timeout";
                return false;
            }
            $line = fgets($this->fp);     // discard the first line of the stream
            return true;
        }
        private function close()
        {
            fclose($this->fp);
        }
        ...
    }
    

    In the above code, I’ve set a timeout of 15 seconds, both for fsockopen() to establish the connection, and for the data stream itself to respond to requests once it is open. It is important to have a timeout for every call to the network because, often enough, the server won’t respond, and we must be able to handle such a freeze.
    I also grab the first line of the stream and ignore it. Usually this just a greeting message from the server, or a confirmation that it is connected. Check your particular mail service’s documentation to make sure this is the case.
    Now we want to run the above code to see that init() is successful:

    include("imap_driver.php");
    // test for init()
    $imap_driver = new imap_driver();
    if ($imap_driver->init('ssl://imap.gmail.com', 993) === false) {
        echo "init() failed: " . $imap_driver->error . "n";
        exit;
    }
    

    Basic IMAP Syntax

    Now that we have an active socket open to our IMAP server, we can start sending IMAP commands. Let us take a look at IMAP syntax.
    The formal documentation can be found in Internet Engineering Task Force (IETF) RFC3501. IMAP interactions typically consist of the client sending commands, and the server responding with an indication of success, along with whatever data may have been requested.
    The basic syntax for commands is:

    line_number command arg1 arg2 ...
    

    The line number, or “tag”, is a unique identifier for the command, that the server uses to indicate which command it is responding to should it be processing multiple commands at once.
    Here is an example, showing the LOGIN command:

    00000001 LOGIN example@gmail.com password
    

    The server’s response may begin with an “untagged” data response. For instance, Gmail responds to a successful login with an untagged response containing information about the server’s capabilities and options, and a command to fetch an email message will receive an untagged response containing the message body. In either case, a response should always end with a “tagged” command completion response line, identifying the line number of the command that the response applies to, a completion status indicator, and additional metadata about the command, if any:

    line_number status metadata1 metadata2 ...
    

    Here is how Gmail responds to the LOGIN command:

    • Success:
    * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS
    COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS
    00000001 OK example@gmail.com authenticated (Success)
    
    • Failure:
    00000001 NO [AUTHENTICATIONFAILED] Invalid credentials (Failure)
    

    The status can be either OK, indicating success, NO, indicating failure, or BAD, indicating an invalid command or bad syntax.

    Implementing Basic Commands:

    Let’s make a function to send a command to the IMAP server, and retrieve the response and endline:

    class imap_driver
    {
        private $command_counter = "00000001";
        public $last_response = array();
        public $last_endline = "";
        private function command($command)
        {
            $this->last_response = array();
            $this->last_endline  = "";
            fwrite($this->fp, "$this->command_counter $commandrn");            // send the command
            while ($line = fgets($this->fp)) {                                   // fetch the response one line at a time
                $line = trim($line);                                             // trim the response
                $line_arr = preg_split('/s+/', $line, 0, PREG_SPLIT_NO_EMPTY);  // split the response into non-empty pieces by whitespace
                if (count($line_arr) > 0) {
                    $code = array_shift($line_arr);                              // take the first segment from the response, which will be the line number
                    if (strtoupper($code) == $this->command_counter) {
                        $this->last_endline = join(' ', $line_arr);              // save the completion response line to parse later
                        break;
                    } else {
                        $this->last_response[] = $line;                          // append the current line to the saved response
                    }
                } else {
                    $this->last_response[] = $line;
                }
            }
            $this->increment_counter();
        }
        private function increment_counter()
        {
            $this->command_counter = sprintf('%08d', intval($this->command_counter) + 1);
        }
        ...
    }
    

    The LOGIN Command

    Now we can write functions for specific commands that call our command() function under the hood. Let’s write a function for the LOGIN command:

    class imap_driver
    {
        ...
        public function login($login, $pwd)
        {
            $this->command("LOGIN $login $pwd");
            if (preg_match('~^OK~', $this->last_endline)) {
                return true;
            } else {
                $this->error = join(', ', $this->last_response);
                $this->close();
                return false;
            }
        }
        ...
    }
    

    Now we can test it like this. (Note that you must have an active email account to test against.)

    ...
    // test for login()
    if ($imap_driver->login('[email protected]', 'password') === false) {
        echo "login() failed: " . $imap_driver->error . "n";
        exit;
    }
    

    Note that Gmail is very strict about security by default: it will not allow us to access an email account with IMAP if we have default settings and try to access it from a country other than the account profile’s country. But it is easy enough to fix; just set less secure settings in your Gmail account, as described here.

    The SELECT Command

    Now let’s see how to select an IMAP folder in order to do something useful with our email. The syntax is similar to that of LOGIN, thanks to our command() method. We use the SELECT command instead, and specify the folder.

    class imap_driver
    {
        ...
        public function select_folder($folder)
        {
            $this->command("SELECT $folder");
            if (preg_match('~^OK~', $this->last_endline)) {
                return true;
            } else {
                $this->error = join(', ', $this->last_response);
                $this->close();
                return false;
            }
        }
        ...
    }
    

    To test it, let’s try to select the INBOX:

    ...
    // test for select_folder()
    if ($imap_driver->select_folder("INBOX") === false) {
        echo "select_folder() failed: " . $imap_driver->error . "n";
        return false;
    }
    

    Implementing Advanced Commands

    Let’s look at how to implement a few of IMAP’s more advanced commands.

    The SEARCH Command

    A common routine in email analysis is to search for emails in a given date range, or search for flagged emails, and so on. The search criteria must be passed to the SEARCH command as an argument, with space as a separator. For example, if we want to get all emails since November 20th, 2015, we must pass the following command:

    00000005 SEARCH SINCE 20-Nov-2015
    

    And the response will be something like this:

    * SEARCH 881 882
    00000005 OK SEARCH completed
    

    Detailed documentation of possible search terms can be found here The output of a SEARCH command is a list of UIDs of emails, separated by whitespace. A UID is a unique identifier of an email in the user’s account, in chronological order, where 1 is the oldest email. To implement the SEARCH command we must simply return the resulting UIDs:

    class imap_driver
    {
        ...
        public function get_uids_by_search($criteria)
        {
            $this->command("SEARCH $criteria");
            if (preg_match('~^OK~', $this->last_endline)
            && is_array($this->last_response)
            && count($this->last_response) == 1) {
                $splitted_response = explode(' ', $this->last_response[0]);
                $uids              = array();
                foreach ($splitted_response as $item) {
                    if (preg_match('~^d+$~', $item)) {
                        $uids[] = $item;                        // put the returned UIDs into an array
                    }
                }
                return $uids;
            } else {
                $this->error = join(', ', $this->last_response);
                $this->close();
                return false;
            }
        }
        ...
    }
    

    To test this command, we will get emails from the last three days:

    ...
    // test for get_uids_by_search()
    $ids = $imap_driver->get_uids_by_search('SINCE ' . date('j-M-Y', time() - 60 * 60 * 24 * 3));
    if ($ids === false)
    {
        echo "get_uids_failed: " . $imap_driver->error . "n";
        exit;
    }
    

    The FETCH Command with BODY.PEEK

    Another common task is to get email headers without marking an email as SEEN. From the IMAP manual, thecommand for retrieving all or part of an email is FETCH. The first argument indicates which part we are interested in, and typically BODY is passed, which will return the entire message along with its headers, and mark it as SEEN. The alternative argument BODY.PEEK will do the same thing, without marking the message as SEEN.
    IMAP syntax requires our request to also specify, in square brackets, the section of the email that we want to fetch, which in this example is [HEADER]. As a result, our command will look like this:

    00000006 FETCH 2 BODY.PEEK[HEADER]
    

    And we will expect a response that looks like this:

    * 2 FETCH (BODY[HEADER] {438}
    MIME-Version: 1.0
    x-no-auto-attachment: 1
    Received: by 10.170.97.214; Fri, 30 May 2014 09:13:45 -0700 (PDT)
    Date: Fri, 30 May 2014 09:13:45 -0700
    Message-ID: <CACYy8gU+UFFukbE0Cih8kYRENMXcx1DTVhvg3TBbJ52D8OF6nQ@mail.gmail.com>
    Subject: The best of Gmail, wherever you are
    From: Gmail Team <mail-noreply@google.com>
    To: Example Test <example@gmail.com>
    Content-Type: multipart/alternative; boundary=001a1139e3966e26ed04faa054f4
    )
    00000006 OK Success
    

    In order to build a function for fetching headers, we need to be able to return the response in a hash structure (key/value pairs):

    class imap_driver
    {
        ...
        public function get_headers_from_uid($uid)
        {
            $this->command("FETCH $uid BODY.PEEK[HEADER]");
            if (preg_match('~^OK~', $this->last_endline)) {
                array_shift($this->last_response);                  // skip the first line
                $headers    = array();
                $prev_match = '';
                foreach ($this->last_response as $item) {
                    if (preg_match('~^([a-z][a-z0-9-_]+):~is', $item, $match)) {
                        $header_name           = strtolower($match[1]);
                        $prev_match            = $header_name;
                        $headers[$header_name] = trim(substr($item, strlen($header_name) + 1));
                    } else {
                        $headers[$prev_match] .= " " . $item;
                    }
                }
                return $headers;
            } else {
                $this->error = join(', ', $this->last_response);
                $this->close();
                return false;
            }
        }
        ...
    }
    

    And to test this code we just specify the UID of the message we are interested in:

    ...
    // test for get_headers_by_uid
    if (($headers = $imap_driver->get_headers_from_uid(2)) === false) {
        echo "get_headers_by_uid() failed: " . $imap_driver->error . "n";
        return false;
    }
    

    Gmail IMAP Extensions

    Gmail provides a list of special commands that can make our life much easier. The list of Gmail’s IMAP extension commands is available here. Let’s review a command that, in my opinion, is the most important one:X-GM-RAW. It allows us to use Gmail search syntax with IMAP. For example, we can search for emails that are in the categories Primary, Social, Promotions, Updates, or Forums.
    Functionally, X-GM-RAW is an extension of the SEARCH command, so we can reuse the code that we have above for the SEARCH command. All we need to do is add the keyword X-GM-RAW and criteria:

    ...
    // test for gmail extended search functionality
    $ids = $imap_driver->get_uids_by_search(' X-GM-RAW "category:primary"');
    if ($ids === false) {
        echo "get_uids_failed: " . $imap_driver->error . "n";
        return false;
    }
    

    The above code will return all UIDs that are listed in the “Primary” category.
    Note: As of December 2015, Gmail often confuses the “Primary” category with the “Updates” category on some accounts. This is a Gmail bug that hasn’t been fixed yet.

    Conclusion

    You’ve got mail. Now what? Read how to build a custom IMAP email client in PHP, and check the mail on your terms.
    Overall, the custom socket approach provides more freedom to the developer. It makes it possible to implement all commands in IMAP RFC3501. It will also give you better control over your code, since you don’t have to wonder what’s happening “behind the scenes.”

    The full imap_driver class that we implemented in this article can be found here. It can be used as-is, and it will take only a few minutes for a developer to write a new function or request to their IMAP server. I’ve also included a debug feature in the class for a verbose output.

  • The Vital Guide to PHP Interviewing

    The Vital Guide to PHP Interviewing

    The Vital Guide to PHP Interviewing

    Ubiquitous…that is definitely one word you could use to describe PHP in relation to the web. It really is everywhere. In terms of server-side programming languages, it is by far the most widely used, powering more than 80% of today’s websites (with the next runner up, ASP.NET, trailing way behind at a mere 17%).
    Why? What makes PHP so popular and widely-used? While there’s no single answer to this question, PHP’s ease of use is certainly a significant contributing factor. PHP newbies can get up-to-speed and build dynamic PHP-based content into their web sites with a minimum of programming expertise required.
    But therein lies much of the challenge of finding highly-skilled PHP developers. PHP’s relatively low barrier-to-entry and 20 year history means that PHP developers have become practically as ubiquitous as the technology itself. Yet while many can legitimately claim to “know” PHP, those who are true experts in the language are capable of producing software that is much more scalable, functional, robust, and maintainable.

    So how do you distinguish those who have real competency in PHP from those with just a cursory knowledge, let alone those who are in the top 1% of candidates?
    Toward that goal, this guide offers a sampling of effective questions to help evaluate the breadth and depth of a candidate’s mastery of PHP. It is important to bear in mind, though, that these sample questions are intended merely as a guide. Not every “A” candidate worth hiring will be able to properly answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains as much of an art as it does a science (see In Search of the Elite Few).
    Note that we have tried to keep this guide focused on modern PHP (i.e., versions 5.3 and beyond), but there are references to concepts and functions that have been around for a long time and should be familiar to any qualified PHP developer.

    Key PHP Concepts and Paradigms

    There are a number of key concepts and paradigms that are essential for a PHP expert to be well-versed in. Here are some examples.
    Q: Describe a closure in PHP. Provide examples of when, why, and how they can be used.
    Closures become useful when some piece of logic needs to be performed in a limited scope but retain the ability to interact with the environment external to that scope. The first building block of a closure is the anonymous, or lambda style, function which has no name associated with it. For example:

    # The 2nd argument to array_walk is an anonymous function
    array_walk($array, function($dog) {
        echo $dog->bark();
    });
    

    Although they themselves have no name associated with them, anonymous functions can be assigned to a variable or passed around as callbacks by higher order functions that require them. For example:

    # Define an anonymous function and assign it to a variable
    # named $dogs_bark.
    $dogs_bark = function($dog) {
        echo $dog->bark();
    }
    array_walk($array, $dogs_bark);
    

    Under the hood in PHP, anonymous functions are implemented using the Closure class.
    The contents of an anonymous function exist within their own scope, independent of the scope in which they were created. However, it is possible to explicitly bind one or more variables from the external scope to be referenceable within the anonymous function via the use clause in the function definition. Let’s illustrate:

    class Dog {
        public function bark() { echo 'woof'; }
    }
    $dogs_bark = function($dog) use (&$collar) { # bind by reference
        if ($collar == 'fitsWell'){
             echo $dog->bark(); # 'woof'
        } else {
             echo 'no bark';    # collar is too tight to bark
        }
    };
    $dog = new Dog;
    $collar = 'fitsWell'; # external variable
    $dogs_bark($dog); # 'woof'
    $collar = 'tight';
    $dogs_bark($dog); # 'no bark'
    

    This ability to access these external variables within a closure becomes particularly useful when using higher order functions. Take for example our array_walk usage from above which, like other functions of this type, operates in a very specific way on the subject variables which it is passed. As the function iterates over the $array, only the current value and key are passed to the anonymous function callback. There is no opportunity to pass in the $collar variable without the closure and it’s use clause . We could use the globalkeyword, but would needlessly pollute the global namespace with a variable that only makes sense in our very limited scope.
    Closures have additional object oriented uses as well. PHP 5.4 brings new methods to the Closure class’ interface. Specifically, the new bind and bindTo methods can be used to bind to new objects for the closure to operate on, e.g.:

    Closure::bindTo($newthis, $newscope);
    

    This method will actually duplicate the closure itself and bind its scope to that new object, so $this actually references $newthis in the object context. To help illustrate, let’s modify the $dogs_bark function to use $this and then bind it to a new Dog object:

    # define the closure, but not bound yet to any object
    $dogs_bark = function() {
        echo $this->sound;  # where this is a property
    };
    $new_dog = new Dog();
    # now create a new closure bound to the $new_dog object
    $new_closure = $dogs_bark->bindTo($new_dog);
    $new_closure();   # echoes the sound
    

    The fact that a closure can be assigned to a variable and now has access to $this is quite powerful. In particular, this means that it can become a callable property of another object and essentially become a method of that object. For example:

    $dog = new Dog();
    $dog->closure = $dogs_bark;
    $dog->closure();
    

    This makes it possible to change and add to the behavioral capabilities of an object at runtime without the need to alter the defining class signature. Very useful when functionality enhancements are needed, but the actual code cannot be touched or where the need for the enhanced functionality is limited in scope.
    Q: Explain the use and purpose of the global keyword in PHP. Provide an example of a case where its use would be appropriate, as well as one where it would not be.
    In the days of “PHP gone by”, the language’s object oriented implementation was much less sophisticated than it is today. It is therefore not uncommon to find older “legacy” PHP code that makes fairly extensive use of the global keyword. In many ways, overuse of global variables “flies in the face” of modern object-oriented programming (OOP) best practices, as it may lead to intertwined dependencies between classes, difficulty decoupling disparate units of logic from one another, and pollution of the global namespace with variables that have no (or very limited) use in that context.
    Consider the following simple example:

    class Dog {
        function bark() {
            global $sounds;
            return $sounds->bark();
        }
    }
    

    This introduces a hidden dependency of the Dog class on the global $sounds object. While there may be cases where this would be justified (e.g., a system with one single well-defined set of sounds that is never modified), generally speaking, it would be much better to explicitly pass the relevant $sounds object to the Dog class’ constructor, which would then be stored and used within that instance of the class; e.g.:

    class Dog {
        protected $sounds;
        function __construct($sounds) {
            $this->sounds = $sounds;
        }
        public function bark() {
            return $this->getSounds()->bark();
        }
        public function getSounds() {
            return $this->sounds;
        }
    }
    

    But as is true with most things in coding, never say never. There are, in fact, a number of robust and stable products out there written in PHP that make heavy use of globals. The WordPress Codex, which powers roughly 20% of the websites on the web (and rising yearly), Joomla! 1.5 (which is still in wide use), and theiLance Enterprise Auction system are all examples of projects that have been around for years and make use of ‘mature’ globals. Similarly, there may be situations where the use of globals in your code is appropriate, but their use should always be approach with caution.
    Q: Describe namespacing in PHP and why it is useful.
    One of the newer additions to PHP’s support for OOP is the namespace. As the name implies, a namespace defines a scope in a program where class, interface, function, variable, and constant definitions won’t produce name collisions with similarly named items in other namespaces.
    Prior to PHP 5.4, class names would often become quite long in an attempt to match the package hierarchy and avoid name collisions. For example, let’s say we have a Dogs class defined in the model of the Dog_Poundapplication. Without namespacing, we might feel compelled to provide a verbose name for our class such as the following:

    class Dog_Pound_Model_Dogs {  # wow, that's a mouthful!
        function getDogs();
    }
    

    Namespacing helps alleviate this issue by enabling the developer to explicitly specify the namespace within which all named items (classes, variables, etc.) are to be defined. With namespacing, the above verbose class name could be replaced with:

    namespace dog_poundmodel;  # specify the current namespace
    class Dogs {   # only "Dogs" defined in dog_poundmodel
        function getDogs();
    }
    $dogs = new Dogs; # unambiguous since only one in this namespace
    

    Relative namespace references are supported as well. For example, when in the dog_pound namespace, you can use the following to instantiate your class:

    $dogs = new modelDogs  # only one "model" defined in dog_pound
    

    In addition, named items in other namespaces can be imported in other files and can then be referenced directly. This is done via the use operator as follows:

    namespace thisnewnamespace;  # our current namespace
    # import Dogs from dog_poundmodel namespace and reference it
    use dog_poundmodelDogs;
    $dogs = new Dogs;
    

    Q: What are traits? Describe their major characteristics and why they are useful. Give an example of a trait declaration and a class that uses multiple traits.
    Traits are an excellent addition to PHP 5.4 that allow behaviors to be added to a class, without needing to extend a parent class to inherit the desired functionality (prior to PHP 5.4, this could only be done via a mixinclass pattern at runtime). Additionally, you can make use of multiple Traits in a single class. This makes them a powerful aid in the organization and separation of concerns in the codebase and, as such, helps to honor thecomposition over inheritance design principle.
    Here are a couple of simple trait definition examples:

    trait Movement {
        public function topSpeed() {
            $this->speed = 100;
            echo "Running at 100 %!" . PHP_EOL;
        }
        public function stop() {
            $this->speed = 0;
            echo "Stopped moving!" . PHP_EOL;
        }
    }
    trait Speak {
        public function makeSound(){
            echo $this->sound . PHP_EOL;
        }
    }
    

    The use keyword is once again employed, this time for importing from another namespace to include one or more traits in a class definition. For example:

    class Dog {
        use Movement, Speak;  // Dog now has these capabilities!
        protected $sound;
        function __construct() {
            $this->sound = 'bark';
        }
    }
    $dog = new Dog();
    $dog->topSpeed();  // from Movement trait
    $dog->stop();      // from Movement trait
    $dog->makeSound(); // from Speak trait
    

    PHP at Your Fingertips

    Committing to memory what can easily be found in a language specification or API document is no indicator of proficiency. But that said, someone who is intimately familiar with a programming language will have its syntactical and functional details and nuances at his or her fingertips. Here are some questions that help evaluate this dimension of a candidate’s expertise.
    Q: Describe the relationship between php://input and $_POST. How would you access the php://inputstream?
    In the simplest terms, the $_POST superglobal is the formatted or parsed content of the body of a request made to the server with the post method.

    POST /php-hiring-guide/php-post.php HTTP/1.1
    Host: toptal.com
    Referer: http:///toptal.php/php-hiring-guide/php.php
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 63
    article_name=PHP Hiring Guide&tag_line=You are hired!&action=Submit
    

    The body of the request can be accessed through the PHP’s input stream the same as any other file:

    $input = file_get_contents("php://input");
    

    Q: Name and define at least five superglobals that begin with $_. Describe their relationship to the $GLOBALS variable.

    • $_POST – a hash of key value pairs sent to the server with the ‘post’ method
    • $_GET – a hash of key value pairs sent to the server with the ‘get’ method
    • $_REQUEST – an amalgamation of $_GET and $_POST
    • $_SERVER – a hash of variables set specifically by the web server, and relevant to the execution of the program
    • $_ENV – a hash of variables related to the host machine and it’s configuration
    • $_SESSION – a hash of variables that are meant to be persisted between page views or separate application executions
    • $_COOKIE – a hash of variables that are to be stored with the client
    • $_FILES – a special type of request hash that holds input data related to an uploaded set of files

    Akin to the global keyword in PHP is the $GLOBALS super global variable. As the name suggests, superglobals are automatic global variables and as such are stored in $GLOBALS. For example, the $_ENV superglobal could alternatively be accessed via $GLOBALS["_ENV"].
    Q: Explain the purpose and usage of the __get, __set, __isset, __unset, __call, and __callStatic“magic” methods. When, how, and why (and perhaps why not) should each be used?
    The first four methods in our list, __get, __set, __isset, and __unset are used for property overloading of an object. They let us define how the outside world is able to interact with properties that have a private or protected visibility, and properties that don’t even exist in our object.

    # 'whiskers' is not defined in the Dog class but is handled by
    # the Dog class' __get method as follows:
    function __get($name) {
        if ($name == 'whiskers') {
            # only create one whiskersService per instance
            if (! isset($this->whiskersService)) {
                $this->whiskersService = new Whiskers($this);
            }
            # so calls to 'whiskers' will load the wiskersService
            return  $this->whiskersService->load();
        }
    }
    

    A caller can then simply retrieve the whiskers property like so:

    $hairs = $dog->whiskers;
    

    By using the __get method to “intercept” this reference to a seemingly public property we are able to obscure the implementation details of one or more of the object’s properties.
    Use of the __set method is similar. For example:

    function __set($name, $value) {
        if ($name == 'whiskers') {
            if ($value instanceOf Whisker) {
                $this->whiskersService->setData($value);
                return $this->whiskersService->getData();
            } else {
                throw new WhiskerException("That's not a whisker");
                return false;
            }
        }
    }
    

    A caller can then simply set the whiskers property like so:

    $dog->whiskers = $hairs;
    

    This statement automatically invokes the __set method, using 'whiskers' as its first argument and the right side of the assignment as the second argument.
    Lastly, the __isset and __unset methods complete the quartet. They each take just one argument, the $name of the property to be evaluated or operated on; e.g.:

    function __isset($name) {
        if ($name == 'whiskers') {
            return (bool) is_object($this->whiskersService) &&
                                    !empty($this->whiskersService->getData());
        }
    }
    function __unset($name) {
        if ($name == 'whiskers' && is_object($this->whiskersService)) {
            # we don't want to completely kill the service:
            $this->whiskersService->reset();
        }
    }
    

    The other two methods, __call and __callStatic, perform a similar function for classes, but give us method overloading. Through their use we can define how a class should react when an undefined, protected, or private method is called.
    In a __call implementation where we we want to ensure all “non-visible” method calls get returned the payload from the whiskersService we might do something like:

    public function __call($method, $args) {
        return $this->whiskersService->load();
    }
    

    __callStatic has the same arguments, the same functionality and allow for this same interaction, but outside of a specific object context. This means that if we have this method defined we can use the ClassName::notVisibleMethod() syntax; e.g.:

    public function __callStatic($method, $args) {
        if (!is_object(static::$whiskersService)) {
            static::$whiskersService = new Whiskers(__CLASS__);
        }
        return static::$whiskersService->load();
    }
    $hairs = Dog::whiskers();
    

    In the above set of examples, we have encapsulated the whiskers implementation from the outside world and made it the only available object exposed in this way. The clients of such properties and methods do not need to know anything about the underlying whiskersService or how the Dogs class is storing its data at all.
    Collectively, these methods increase our ability to flexibly compose objects. The opportunity for object abstraction and encapsulation, and thus reusable, more compact code (and ultimately a more manageable system as a result) are also increased.
    Care should be taken, though, in using these convenient methods, as the benefits can come at a cost. They are slower than straight access to an otherwise public property in question, and also slower than defined getters and setters. They also hamper use of certain useful capabilities (such as object reflection, autocomplete in your IDE, automatic documentation utilities like PHPDocumentor, and so on). So if these are facilities you want or need to rely on, you may consider defining methods and properties explicitly instead. As with most things, there’s no across-the-board right answer. The pros and cons should be evaluated on a case-by-case basis.
    Q: Describe one or more Standard PHP Library (SPL) data structures. Give usage examples.
    Most of PHP development deals with getting and processing data from one source or another, such as a local database, local files, a remote API, etc. As such, developers spend a great deal of time getting, organizing, moving, and manipulating that data. In some cases, an array just won’t cut it in terms of memory usage and performance and therefore better data structures are called for.
    Also, with so much talk and focus on frameworks (this page could be filled with names of PHP frameworks!), it could be difficult to find a developer who has a great deal of experience with the particular framework that your project is using. The net effect of a such an active development community is that the distribution of developers working with a particular framework starts to shrink, and could make it harder for you to find that specific skill.
    One area to focus on, and where you be reasonably sure that a PHP expert will have familiarity, is in the use of and general makeup of the Standard PHP Library (SPL). If the candidate has a solid background here, the chances of success for that candidate working into and adding value to your application are greater, regardless of the specific frameworks being used in your environment.
    Specifically, a candidate should be familiar with some or all of the nine SPL data structures listed in the PHP Manual. Many provide highly similar functionality to one another, but the slight variations make each one more perfectly suited to a particular use. Here’s a brief overview:

    • SplDoublyLinkedList. Each element in this list holds links to the node before it and the node after it in the list. Picture that you are on line at the bank, but you are only able to see the person in front and the person behind you. That is analogous to the ‘link’ relationship between elements in a SplDoublyLinkedList. Inserting an element into the list is akin to someone cutting in front of you at the bank (but you then suddenly forget who was in front of you, and that person also forgets you entirely). Enables efficient transversal through a dataset and lets you list and add large amounts of data, with no internal need to re-hash.
    • SplQueue and SplStack. Very similar to the SplDoublyLinkedList are the SplQueue and SplStack. Both of these are essentially SplDoublyLinkedLists with different iterator flags (IT_MODE_LIFO is “Last In First Out” and IT_MODE_FIFO is “First In First Out”), which govern which order the elements are read in and what to do with those elements after they have been processed. One other distinction is that the SplQueue API might be considered a bit more intuitive, supplying an enqueue() method (rather than push()) and a dequeue()method (rather than shift()).
    • SplHeap. Represented internally as a binary tree, where each node in the tree has a maximum of two child nodes. It is an abstract class which must be extended to define a compare() method. This method is then used to perform real time sorting whenever a value is inserted into the tree.
    • SplMaxHeap and SplMinHeap. Concrete implementations of the SplHeap abstract class. SplMaxHeapprovides a compare() method that maintains values in order from highest to lowest, whereas SplMinHeapprovides a compare() method that maintains values in order from lowest to highest.
    • SplPriorityQueue. Similar to an SplHeap, but sorting is done based on an additional “priority” value supplied for each member.
    • SplFixedArray. Similar to a regular array, but indices can only be integers and the length of the array is fixed. It provides improved speed when implementing an array. There is no processing speed benefit over an array, the interface is optimized so that the objects don’t need to be hashed manually when adding elements.
    • SplObjectStorage. Provides an interface for mapping objects to data or simply providing a container for a set of objects. Essentially, it can use an object much like an associative array key to relate that object to some data or to no data at all.

    Q: What will $x be equal to after the statement $x = 3 + "15%" + "$25"?
    The correct answer is 18. Now let’s explain why.
    PHP supports automatic type conversion based on the context in which a variable or value is being used.
    If you perform an arithmetic operation on an expression that contains a string, that string will be interpreted as the appropriate numeric type for the purposes of evaluating the expression. So, if the string begins with one or more numeric characters, the remainder of the string (if any) will be ignored and the numeric value is interpreted as the appropriate numeric type. On the other hand, if the string begins with a non-numeric character, then it will evaluate to zero.
    With that understanding, we can see that "15%" evaluates to the numeric value 15 and "$25" evaluates to the numeric value zero, which explains why the result of the statement $x = 3 + "15%" + "$25" is 18 (i.e., 3 + 15 + 0).
    Depending on who you ask, automatic type conversion is either a great feature or one of the worst pitfalls of the PHP language. On the one hand, when used consciously and properly, it can be very convenient for the developer (e.g., I don’t need to write any code to convert “15” to 15 before using it in an arithmetic operation). On the other hand, it can easily lead to headfakes and hard-to-track-down bugs when it is employed inadvertently, since no error message or warning will be generated.
    Q: Explain the significance of using the static keyword when invoking a method or property, including how it differs from the self keyword? When would you use it and why? Provide an example.
    As of PHP 5.3.0, PHP implements a feature called late static bindings. “Late binding” comes from the fact that static:: will not be resolved using the class where the method is defined but will rather be determined using runtime information and scope. (Incidentally, the term “static” is a bit of a misnomer in that this is not limited to being used with static methods.)
    Consider the following example:

    class Dog {
        static $whoami = 'dog';
        static $sound = 'bark';
        function makeSounds() {
            echo self::makeSound() . ', ';
            echo static::makeSound() . PHP_EOL;
        }
        function makeSound() {
            echo static::$whoami . ' ' . static::$sound;
        }
    }
    Dog::makeSounds();
    

    Unsurprisingly, this will output “dog bark, dog bark”.
    But now let’s extend this example to include the following:

    class Puppy extends Dog {
        static $whoami = 'puppy';
        static $sound = 'woof';
        function makeSound(){
            echo static::$whoami . ' whimper';
        }
    }
    Puppy::makeSounds();
    

    You may be surprised to learn that this will output “puppy woof, puppy whimper”. To understand why, let’s revisit the makeSounds() method in the Dog class.
    The makeSounds() method in the Dog class first invokes self::makeSound(). self:: instructs PHP to always use the scope of the same class (in this case, the Dog class). Therefore, calling self::makeSound() from within Dog’s makeSounds() method will always invoke Dog’s version of makeSound(). This is true even when we call Puppy::makeSounds() since Puppy has no makeSounds() method of its own and instead relies on Dog’s version. This is why the call from Puppy::makeSounds() to self::makeSound() outputs “puppy woof”.
    Next, the makeSounds() method in the Dog class invokes static::makeSound(). static:: behaves differently from self::. static:: instructs PHP to use the version in the scope of the class that invoked the method at runtime (in this case, the Puppy class). Hence, when the call to static::makeSound() is made, it invokes Puppy’s version of that method. This is why the call from Puppy::makeSounds() to static::makeSound() outputs “puppy whimper”.

    PHP Under-the-Hood

    Understanding how PHP works “under the hood” is one of the primary defining characteristics of a PHP expert. Such a candidate will understand not only how to do something, but the various options available, and the performance and functional ramifications of each.
    Q: How does PHP build an array internally?
    Central to much of PHP development is the array. These are good for most uses where an iterable data structure is needed. Internally in PHP, arrays are stored, like many other data structures, as hash tables. PHP is written in C where there is no such thing as an associative array: arrays in C can only have integer indices. Therefore, a hash function is used to translate PHP array indices (both integer and string) into appropriate numeric indices and the array values are stored at that location or bucket in the hash table.
    The process of finding bucket entries based on a hash of the array keys is of O(1) complexity (using Big O notation). This because no iteration over the hash is needed, since the hash function produces the exact location in the table. (Note that this changes slightly if there is more than one element in the bucket.)
    PHP automatically increases the size of an array “on demand”. Specifically, when an element is added to an array, if addition of the element would cause the array to exceed its currently allocated size, PHP responds by doubling the memory allocation. The corresponding hash table needs to be completely rehashed as a result.
    Let’s consider what that means for just a second: Adding values to an array can in some cases be as complex as iterating over that entire new array, and in that same situation you have doubled the memory footprint of that structure. Given this, where datasets begin to get large and memory is an issue, it may be wise to consider an alternative to an array, where loading the data for processing happens on a more as needed basis.
    Q: What is the difference between the ArrayAccess and ArrayObject?
    ArrayAccess is simply an interface definition that requires any class that implements it to define the following methods: offsetGet, offsetSet, offsetExists, and offsetUnset.
    ArrayObject, on the other hand, is an instantiable class that implements the ArrayAccess interface. A nice usage convenience of an ArrayObject is that its elements can either be accessed the same as a standard array (i.e., via the familiar [] notation; e.g., $dogs['sound']) or via the offsetGet(propertyName) method (e.g., $dogs->offsetGet('sound')).
    Q: What is a generator? When might you use it instead of an iterator or a plain array. What do yield and send do?
    A generator looks much like any other function in PHP and shares some similarities with closures. When called for the first time in an iterable context (e.g., a foreach statement), the generator returns an object that is an instance of the Generator class, which in turn implements the Iterator interface. The values for iteration are generated in real-time eliminating the need to load an entire data set into memory before hand. That means that the result can be iterated over in much the same way that an array can, but with some important differences; namely they:

    • Can only be used in a forward run, meaning that one can’t iterate backwards over the values or start at the beginning. Calling the rewind() method on the generator will throw an exception.
    • Are slower than processing a pre-populated array (the generator is doing extra processing to produce the value).
    • Are extremely memory efficient.

    One of the chief differences between a generator function and other PHP functions or closures is that they don’t make use of return to provide their results. Instead, yield is used to pass values out of the generator (e.g., yield $dog;). In fact, specifying a value on a return statement in a generator will produce a parser error, but an empty return statement will simply stop the generator altogether.
    yield pauses execution and returns the current value to the scope of the structure that is using the generator. That structure has the opportunity to send information back to the generator at that same point in its execution via the send method (e.g., $generator->send(-1);).
    With that basic explanation, let’s take a look at a simple example of a generator’s use.
    First, let’s define our generator:

    function dog_generator() {
        foreach (range(0, 2) as $value) {
            # some fake data source
            $dog = DogHelper::getDogFromDataSource($value);
            # catch input from send or use $dog
            $input = (yield $dog);
            if ($input == -1) {
                return; // stop the generator
            }
        }
    }
    

    Note that, in the above example, we are assigning the result of the yield method call to a variable and must therefore wrap the yield in parentheses in order for it to be syntactically valid.
    And now here’s an example of how we would use the above generator:

    # Get an instance of the generator and assign it to a variable
    $generator = dog_generator();
    foreach ($generator as $dog) { # $dog is a result of 'yield'
        echo $dog . PHP_EOL;
        // we wanted to find the terrier
        if ($dog == 'Terrier') {
            # send an input into the generator via 'yield'
            $generator->send(-1);
            echo 'We found the Terrier, stop the show.';
        }
    }
    

    When we run the above code our example stops when it finds “Terrier”. For example:

    Dalmatian
    Terrier
    We found the Terrier, stop the show.
    

    The key benefits of a generator are ease of implementation, increased readability of code, and overall improved performance and memory usage.
    So generally speaking, it’s best to use a generator where there is no need to rewind or iterate back over the values again in another part of the program. On the other hand, if memory is not a concern, then a simple array of the values is much faster.

    The Big Picture

    Q: List some of the major differences between (or sequential additions and improvements to) PHP 5.3, PHP 5.4 and PHP 5.5.
    PHP 5.3 was released back in June 2009 but is still in wide circulation. Key new features in this release included: closures, lambda style functions, namespacing, and late static binding.
    PHP 5.4 was released in March 2012, introducing Traits, as well as the ability to declare an array with a shortened [] syntax (e.g., $array = ['shih tzu', 'rottweiler']). In addition, register_globals was removed in this version.
    PHP 5.5 was released in June 2013 and is the current release. This version adds support for generators (and their related yield and send keywords), as well as adding finally to the try/catch exception handling syntax. APC Cache is gone in favor of OpCache (based on the Zend Optimizer). PHP 5.5 also takes the array literal even further and supports syntax such as ['shih tzu', 'rottweiler'][1] (which returns “rottweiler”) as well as the handy notation of strings interpreted as arrays (e.g., '6, 5, 4'[0], which returns “6”).

    Wrap-up

    Finding PHP developers can be relatively easy, but finding stellar PHP developers is a formidable challenge. The questions presented in this guide can serve as useful tools in your overall recruiting toolbox to better identify those who have mastered the language. Finding such candidates is well worth the effort, as they will undoubtedly have a significant positive impact on your team’s productivity and results.

  • Show limited words in PHP from string with HTML tags

    Hi,
    Here i have create another function called “truncate”.
    With this function you can show limited words with HTML tags. I know there is a function in PHP “SUBSTR”. but the main issue i face with this is this will also remove HTML tags, which mean when any tag starts then that tags will not close. support here is my string:

    <h1>HI this is a </h1> random string to show <a href="">a dummy text</a>

    now when i use substr like this:

    <?php
    $string='<h1>HI this is a </h1> random string to show <a href="">a dummy text</a>';
    echo substr($string,0,40);
    ?>

    so in the outout it remove closing tag. this mean the rest of content become a link.
    so i create this function, now this function will add the tags when any tags will not close.

    <?php
    function truncate($text, $length, $suffix ='', $isHTML = true) {
    $i = 0;
    $simpleTags=array('br'=>true,'hr'=>true,'input'=>true,'image'=>true,'link'=>true,'meta'=>true);
    $tags = array();
    if($isHTML){
    preg_match_all('/<[^>]+>([^<]*)/', $text, $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
    foreach($m as $o){
    if($o[0][1] - $i >= $length)
    break;
    $t = substr(strtok($o[0][0], " \t\n\r\0\x0B>"), 1);
    // test if the tag is unpaired, then we mustn't save them
    if($t[0] != '/' && (!isset($simpleTags[$t])))
    $tags[] = $t;
    elseif(end($tags) == substr($t, 1))
    array_pop($tags);
    $i += $o[1][1] - $o[0][1];
    }
    }
    // output without closing tags
    $output = substr($text, 0, $length = min(strlen($text), $length + $i));
    // closing tags
    $output2 = (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : '');
    // Find last space or HTML tag (solving problem with last space in HTML tag eg. <span class="new">)
    $splitted = preg_split('/<.*>| /', $output, -1, PREG_SPLIT_OFFSET_CAPTURE);
    $last_item = end($splitted);
    $pos = end($last_item);
    // Append closing tags to output
    $output.=$output2;
    // Get everything until last space
    $one = substr($output, 0, $pos);
    // Get the rest
    $two = substr($output, $pos, (strlen($output) - $pos));
    // Extract all tags from the last bit
    preg_match_all('/<(.*?)>/s', $two, $tags);
    // Add suffix if needed
    if (strlen($text) > $length) { $one .= $suffix; }
    // Re-attach tags
    $output = $one . implode($tags[0]);
    //added to remove unnecessary closure
    $output = str_replace('</!-->','',$output);
    return $output;
    }
    ?>

    now how to use it?

    <?php
    $string='<h1>HI this is a </h1> random string to show <a href="">a dummy text</a>';
    echo truncate($string,40);
    ?>

    Try it.
    I hope this code will help you..

  • SEO friendly URL generator

    Hi, here is a function which I create for generating SEO friendly URL.
    first we have to create a function called “friendlyURL”.
    here is a code

    <?php
    function friendlyURL($inputString){
    $url = strtolower($inputString);
    $patterns = $replacements = array();
    $patterns[0] = '/(&amp;|&)/i';
    $replacements[0] = '-and-';
    $patterns[1] = '/[^a-zA-Z01-9]/i';
    $replacements[1] = '-';
    $patterns[2] = '/(-+)/i';
    $replacements[2] = '-';
    $patterns[3] = '/(-$|^-)/i';
    $replacements[3] = '';
    $url = preg_replace($patterns, $replacements, $url);
    return $url;
    }
    ?>

     
    Now this function will convert string into a SEO friendly URL.
    How to use it?

    <?php
    echo friendlyURL('hi this is a seo friendly url & it convert/replace special characters.');
    ?>