
Quite often I have a snippet of PHP code that I’ve quickly typed out, maybe a string builder or something like that, and I need to test it, but I want to test it on its own, without the rest of the script being executed alongside it. Enter the wonderful world of online PHP interpreters then. Basically these guys allow you to enter some PHP code into a box on a webpage, which then gets evaluated (i.e. executed), and the console result of which is returned to you. Simple. My most often used of these services is the simple but extremely useful PHP CodePad, written by Ajay Kwatra. Well worth checking out if you ever need to check that the result of say “date(‘d/m/Y’,strtotime(‘-2 days’))” is exactly what you were hoping for! :) Related Link: http://phpcodepad.com/
It is not very common but sometimes you’ll find yourself working on a project that features multiple databases holding all the information we need. Now of course we know that when making an initial database connection we get a identifier on a successful connect, which we can then pass along to a mysql_query call as a parameter in order to force that query to happen on that particular database connection: And this will work 99% of the time. However, there is one instance when it won’t work, and is guaranteed to trip you up if you’ve never encountered this before. If you are using the same hostname, username and password across your databases, in other words the arguments passed to your mysql_connect call remains the same, mysql_connect will in fact not open a new connection on your secondary connect to another database, and instead just pass you the identifier it came up with on your first connect. Obviously this will break your code because the database you’re interested in using doesn’t exist on this first connection! Luckily to get around this limitation is pretty simple. The mysql_connect function has an often neglected boolean parameter known as $new_link which if set to true, will force a new connection to be created regardless of whether or not the parameters for this connect request matches those of your previous connect request And now you know. Not that this scenario should happen very often mind you…

Given a string, it would often be quite useful to extract any e-mail addresses that it might contain. Luckily for us, PHP makes this fairly trivial through the use of its powerful filter_var functionality. Essentially the plan of attack is to take the string, tokenize it by breaking it up on the space character (or whatever other delimiters you wish to use), and then loop through each one of those tokens and check if it matches a recognised email address pattern. Putting all of this together, we would get a function which looks a little like this: To test: Nifty.

An often overlooked tweak when cleaning a user or system input string is to make sure that there aren’t any double, triple or basically multiple instances of a space character next to one another, possibly caused by string concatenation or just a sticky spacebar key. Below is a handy little function which works in a recursive manner to ensure that our input string only contains single instances of the space character: Simple in design, but it gets the job done. (Of course, it might have been even easier to achieve this through some nifty regex one could argue…)
At some point in time with the newer versions of PHP, a lot of you would see this warning spit out by your PHP installation every time you called a date related function: “It is not safe to rely on the system’s timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘UTC’ for ‘Africa/Johannesburg’ instead”. What it is basically telling you is that you need to explicitly set the timezone which PHP is to use, instead of just letting it run with whatever the server was using as you used to do in the past. To do this you have two choices, which if you had bothered reading the warning message, would have been given to you on a platter. The first option you would use on a script by script basis, which of course doesn’t really make all that much sense. Basically, call the date_default_timezone_set() function and set it to a timezone string of your choice. The second option, and the one which makes the most sense is to set the default timezone in the php.ini configuration file itself, using the date.timezone declaration. In practice: … date.timezone = ‘Africa/Johannesburg’ Nifty. Related Link: http://php.net/manual/en/function.date-default-timezone-set.php

The shortening of URLs has become quite popular as the advancement of mobile phones picked up speed, and for the most part the science of generating a short URL given a long URL is pretty elementary stuff. Today’s PHP function looks at how one can quickly generate a short URL from a long URL by making use of Google’s excellent URL Shortener API. Now of course, requests to the Google URL Shortener API for public data must be accompanied by an identifier, which can be an API key or an auth token. 99% of the time an API key will suffice for your purposes, so to acquire an API key, visit the APIs Console and in the Services pane, activate the Google URL Shortener API. Next, go to the API Access pane. The API key is near the bottom of that pane, in the section titled “Simple API Access.” After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs. Note that the API key is safe for embedding in URLs – it doesn’t need any encoding. Now that we have our API key, let’s take a look at the function which is going to generate our Short URLs for us: //generate a short URL using Google URL Shortening API function googleGenerateShortURL($longurl) { //result object to be returned at the end of the function $result = array(‘status’ => ’0′, ‘short-url’ => ”, ‘long-url’ => ”, ‘message’ => ‘Failed to shorten URL.’); if (strlen($longurl) [...]
PDO is a popular way of managing database connections and activities in the LAMP stack, though it isn’t always turned on by default unfortunately. Lucky for us, the following simple PHP code snippet runs a simple enough check and then alerts us to the status, making it a breeze to pick up on whether of not PDO is actually available or not. if (!defined(‘PDO::ATTR_DRIVER_NAME’)) { echo ‘PDO unavailable’; } elseif (defined(‘PDO::ATTR_DRIVER_NAME’)) { echo ‘PDO available’; } Simple but rather effective.
Almost unbelievably so, PHP doesn’t actually feature a neatly named insert into array function (to be fair though, it doesn’t have a neatly named remove from array function either!). However, inserting values into an array is actually possible, though to do this we need to make use of the array_splice (remove a portion of the array and replace it with something else) function – in a slightly warped way of course. The more complete manual description: array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] ), with the text: Removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied. By leveraging the fact that the function accepts a length input to control just how much of the array gets chopped out, we can in fact insert our new values into an existing array by simply pointing at the required offset in the array where we wish to insert our new values, and make use of a zero length value to ensure that no existing elements get dropped out. In practice: $input = array(“red”, “green”, “blue”, “yellow”); array_splice($input, 3, 0, “purple”); // $input is now array(“red”, “green”, “blue”, “purple”, “yellow”); $input = array(“car”, “truck”, “bus”, “train”); array_splice($input, 1, 0, array(“motorbike”,”taxi”)); // $input is now array(“car”, “motorbike”, “taxi”, “truck”, “bus”, “train”); Nifty. Related Link: http://www.php.net/manual/en/function.array-splice.php
I tried installing the useful open-source invoice management web application Siwapp the other day, and on trying to run the install script I kept getting shot down with a “Fatal error: Class ‘PDO’ not found in…” error message. Some time spent on Google informed me that the problem lies in the fact that the popular PDO database handling extensions weren’t installed properly on my web server, despite PHP info telling me explicitly that the version of PHP which the server was running was compiled with PDO support. Anyway, after some digging around on the ‘Net, I found the quick way of solving this issue, pretty much through adding some lines to your existing php.ini configuration file. So, after opening up the relevant php.ini file via my server’s cPanel installation, I added the following lines to the bottom of the file, in the extensions section of the .ini file: extension=pdo.so extension=pdo_sqlite.so extension=sqlite.so extension=pdo_mysql.so extension=php_pdo.dll Obviously, you don’t have to add all the database types if say your application only uses MySQL. You might have to restart your webserver, though this is doubtful, and as long as your version of PHP has been compiled to support PDO, you should now be free of the dreaded “Fatal error: Class ‘PDO’ not found in…” message. (phpinfo should give you some more information about what PDO functionality you now have access to). Nifty.
To learn the offset or array key for a specific array element in a given array turns out to be fairly easy, thanks to the extra search parameter that the always useful array_keys (return all the keys or a subset of the keys of an array) function offers us. From the manual description: array array_keys ( array $input [, mixed $search_value = NULL [, bool $strict = false ]] ) – array_keys() returns the keys, numeric and string, from the input array. If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned. Knowing this, we can now find exactly where a specific element sits by simply entering a search value when calling the array_keys function, which in practice would look something like this: $array = array(“blue”, “red”, “green”, “blue”, “blue”); print_r(array_keys($array, “blue”)); /* Array ( [0] => 0 [1] => 3 [2] => 4 ) */ The above example shows us that the array element “blue” appears at offset 0, 3 and 4 in the source array. Nifty. Related Link: http://www.php.net/manual/en/function.array-keys.php
A lot of web services provide you with some useful JSON formatted data in exchange for a few parameters or just some love, and this is a particularly simple and easy method to grab some of that JSON goodness for use in your own PHP page. In order to grab the data, we’ll first create a HTTP stream content where we’ll add the all important X-Request-With = XMLHttpRequest header that is used to identify requests as being AJAX requests. At this point you can add any parameters you wish to hit the web service with by adding them as an associative array and wrapping them in a http_build_query() call for the context content. The next step is to use the classic file_get_contents (this assumes your apache/PHP allows the use of the function to open URLs) to hit the target URL using the newly created context. This should work, resulting in a JSON object which you can use PHP’s json_decode function to manipulate. In action: $opts = array(‘http’ => array( ‘method’ => ‘POST’, ‘header’ => “Content-type: application/x-www-form-urlencoded\r\nX-Requested-With: XMLHttpRequest\r\n”, ‘content’ => http_build_query(array()) ) ); $context = stream_context_create($opts); $result = file_get_contents(“http://webservice.org/route/list/key/mykey/format/json”, false, $context); $jsondata = json_decode($result, true); Nifty.
JSON has become just as big as XML in terms of being the format used to transfer data between AJAX driven web services, meaning that as a PHP developer you will no doubt be doing a lot of dealing with JSON objects. The default way of grabbing JSON data returned by a web service is to call the built in json_decode function which generates what is known as a stdClass. These can be traversed much as you would a normal array using loops: $jsondatastdclass = json_decode($jsoninput); print_r($jsondataarray); foreach ($jsondatastdclass as $object) { foreach ($object as $property=>$value) { echo $property.” has the value “. $value; } } It’s not great, but it does work. However, later version of PHP do allow you to add a second parameter when calling the json_decode function, namely a boolean which then forces the function to return a normal associative array. In practice: $jsondataarray = json_decode($jsoninput, true); print_r($jsondataarray); echo $jsondataarray['data'][0]; And now you know.

“Warning: stream_socket_enable_crypto(): this stream does not support SSL/crypto” is a message you will often come across when doing mail send work in PHP, particularly when your SMTP settings require you to connect using either a SSL or TLS mode. The reason for the PHP warning message is actually not insidious at all – 99% of the time it refers to the fact that the OpenSSL extension hasn’t been enabled in your PHP configuration file – and under XAMPP this is almost always the case. So a simple fix is to navigate to your php.ini file (for XAMPP it usually sits under xampp\apache\bin\php.ini), open it up and run a search for “extension=php_openssl.dll”. Uncomment this line by removing the semi-colon at the front of it, save the file and then restart Apache via the Services panel. Nifty.

The cURL library is a useful tool that allows you to connect and communicate to many different types of servers with many different types of protocols. If you implement a cURL operation in your PHP code and the web page spits out a “Fatal error: Call to undefined function: curl_init()” error message back at you, then it is probably safe to assume that the cURL library is currently included in your Apache, PHP stack. (To verify this, run a phpinfo() call and then search for ‘curl’. If it isn’t installed, then the search should return nothing). To install cURL in Ubuntu 12.04 using a terminal, enter: If the status messages returned after the two operations have completed look all successful, rerun your phpinfo() call and you should now be able to find a couple of curl entries on the resulting page. Nifty.
Date work is always icky, but luckily PHP has some pretty nifty functions that can pretty much do all the heavy lifting for you. One of most commonly faced problems is how to add either a number of days, months or years to a given date, and thanks to PHP’s fantastic strtotime function and its natural language (well sort of) parsing, this becomes pretty trivial to solve. Taken from the PHP manual: The strtotime function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied. To see it in action against the current date, try running: Of course, if you want to use a different base for its calculations, you would use the function like so: Nifty. Related Link: http://php.net/manual/en/function.strtotime.php

To generate a string containing a random selection of both letters and numbers (i.e. an alphanumeric string) using PHP is pretty trivial. Essentially what we want to do is define a string containing all the characters we wish to use in the generated string. Then randomly select characters from the string and glue them all together until we get a random string of the desired length. Coded as a function, you get: Pretty simple, but quite useful actually.

If you are working with a small to medium data set and want to draw a random selection of prize winners from your collected data, this small PHP prize draw snippet works pretty well and is nice and should be pretty simple to adapt to your needs. The idea here is to run a SQL statement to give you a list of all the unique customers in the identified data set, build two arrays, the first a keyed array with the customer’s details for printing purposes and a second containing their unique identifier ID key. The second array will be checked to ensure that only unique keys are contained, then shuffled using PHP’s built in shuffle function, before finally slicing off the desired amount of winners (remembering to pad this number ever so slightly so that we can generate both a winners list as well as a backup list for when winners can’t be contacted). So very simple, but as you will find, pretty damn effective. In this sample code, my database contains surveyors in a surveyors table and survey data in a surveys table. And that’s that. Simple, but effective.
Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under whichever martial arts dojo is closest at the time, and for the most part, simply enjoys life with his amazing wife and daughter.
Oh, and he draws ever now and then too.
This is a collection of things that he has managed to find the time to scribble down since 2007.
Looking for Something?
Jump to Category: