Welcome to the Boolean blog

Here you will find details of news, projects, releases and other bits and pieces that we are working on at Boolean. We hope that you find something of interest amongst the archives.

Code snippets, methodologies and useful links will also be mentioned here.

Where there is more to logic than TRUE or FALSE

Archive for 'PHP'

Currency Conversion using Yahoo Finance API

Just a quick and dirty PHP function to retrieve information from the Yahoo Finance API to perform a currency conversion

function ConvertCurrency($From,$To,$Amount){
$URL = ‘http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=’. $From . $To .’=X’;
$Handle = @fopen($URL, ‘r’);

if ($Handle) {
$Result = fgets($Handle, 4096);
fclose($Handle);
}
$allData = explode(‘,’,$Result);
$Value = $allData[1];

return $Value * $Amount;
}

Usage:

$Amount = ConvertCurrency(“NZD”,”USD”,25);

PHP Script Execution Timer Class

Often for testing the efficieny of some PHP code we use script execution calculations such as the microtime function. What is infinitely more useful however is the ability to time the execution of all, some, or multiple sections of code or series of lines.
Unfortunately I cant remember the origins of this timer class – but this code allows you to stop, start, pause and resume timing of specific sections of your php code. Thank you, whoever you may be.

Download the class here

Available methods:

start() – start/resume the timer
stop() – stop/pause the timer
reset() – reset the timer
get([$format]) Which can defaults to Timer::SECONDS but can also be Timer::MILLISECONDS or Timer::MICROSECONDS

Usage example:

$timer1 = new Timer();
$timer2 = new Timer();

$timer1->start();
// do some code

// calculate the time it takes to run a function
$timer2->start();
functionX();
$timer2->stop();

$timer1->stop();

print $timer1->get();
print $timer2->get();

cURL in PHP to access protected sites

So I was trying to use the FaceBook PHP-SDK and ran into an issue. As the cURL was pointing to an HTTPS source I was getting this error:

Failed: Error Number: 60. Reason: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

The problem was that cURL hasnt been configured to trust the servers HTTPS certificate, as by default cURL is not setup to trust any of the Certificate Authorities (CAs)
Browsers dont have this issue as the browser developers were kind enough to include a list of default CAs, however this doesnt help us out at all…

A quick fix is to simply configure cURL to accept any server certificate. Obviously from a security point of view this isnt great, but if you are not passing sensitive information back and forth you should be ok.

Before calling curl_exec() add the following code:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

This causes cURL to blindly accept an server certificate without doing any verification with the CA that issued it.

The Proper Fix
The proper fix is slightly more involved so I plan to cover it at a later stage. If you cant wait that long research the curlopt_cainfo parameter, and obtaining (and saving) a CA certificate to enable cURL to trust it.

PHP URL Shortening

A current Twitter related project involves quite a few URLs and because Twitter limits you to only 140 characters per post shortening a link can be very rewarding.

There are a multitude of URL shortening services on the internet and whilst perhaps not producing the shortest links, TinyURL.com requires no account in order to use it via PHP which makes for a very simple query:
function getTinyUrl($url) {
return file_get_contents(“http://tinyurl.com/api-create.php?url=”.$url);
}


bit.ly is another popular URL shortener, however it does require an easily obtainable API key. The code is below:
function getBitly($url) {
$query = file_get_contents(“http://api.bit.ly/v3/shorten?login=YOUR_LOGIN&;apiKey=YOUR_APIKEY&longUrl=”.$url.”&format=xml”);
$element = new SimpleXmlElement($query);
$bitlyurl = $element->data->url;
if($bitlyurl){
return $bitlyurl;
} else {
return ’0′;
}
}

Dont forget to change YOUR_LOGIN and YOUR_APIKEY to your own values. I’m sure you dont need any help with usage, but as always comment if you have any issues.

PHP Arrays

Recently I had to refactor a few quite old CRON jobs which made extensive use of arrays within loops.

As usual with old code I had to brush up a little as a reminder so thought I would summarise a few quick notes:

sort() and rsort() are for sorting indexed arrays
asort() and arsort() are for sorting associative arrays
ksort() and krsort() are for sorting associative arrays by key
array_multisort() is for sorting multiple related arrays and multidimensional arrays

The PHP sort() function sorts values contained within an indexed array in ascending order.
This means that A-Z, and 0-9. Uppercase letters come before lowercase letters, and all letters come before numbers.

$testArray = array( 1, 2, 3, ‘a’, ‘b’, ‘c’, ‘A’, ‘B’, ‘C’ );
sort( $testArray );

// Displays “A B C a b c 1 2 3″
foreach ( $testArray as $value ) echo “$value “;

rsort() works exactly the same as sort(), except that it sorts in descending order.

$testArray = array( 1, 2, 3, ‘a’, ‘b’, ‘c’, ‘A’, ‘B’, ‘C’ );
rsort( $testArray );

// Displays “3 2 1 c b a C B A”
foreach ( $testArray as $value ) echo “$value “;

Sorting associative arrays using asort() and arsort()

sort() and rsort() are great for indexed arrays where you usually do not care about the relationship between keys and values; however with an associative array they can cause problems:

$book = array( “title” => “Lord Of The Rings”, “author” => “J.R.R. Tolkien”, “year” => 1954 );
sort( $book );

// Displays “Array ( [0] => J.R.R. Tolkien [1] => Lord Of The Rings [3] => 1954 )”
print_r( $book );

As you can see, the sort() function has reindexed the array with numeric indices and in the process destroyed the original string indices of “title”, “author”, and “year”.

To sort values in an associative array whilst preserving keys, use asort() and arsort() instead as these functions preserve not only the keys, but also the relationship between keys and their values.

$book = array( “title” => “Lord Of The Rings”, “author” => “J.R.R. Tolkien”, “year” => 1954 );
asort( $book );

// Displays “Array ( [author] => J.R.R. Tolkien [title] => Lord Of The Rings [year] => 1954 )”
print_r( $book );

Sorting associative arrays by key using ksort() and krsort()

As well as sorting an associative array by value it can also be sorted by key. ksort() sorts the elements in ascending key order, while krsort() sorts in descending key order.

Just like asort() and arsort() these functions will preserve the relationship between key and value.

$book = array( “title” => “Lord Of The Rings”, “author” => “J.R.R. Tolkien”, “year” => 1954 );
ksort( $book );

// Displays “Array ( [author] => J.R.R. Tolkien [title] => Lord Of The Rings [year] => 1954 )”
print_r( $book );

krsort( $book );
// Displays “Array ( [year] => 1954 [title] => Lord Of The Rings [author] => J.R.R. Tolkien )”
print_r( $book );

So far, so good, – so lets move onto multidimensional arrays.

Sorting multiple arrays and multidimensional arrays with array_multisort()

The PHP array_multisort() function sorts multiple related arrays in one run whilst preserving the relationships between the arrays, and it can also sort multidimensional arrays.

$directors = array( “James Cameron”, “Ethan Cohen”, “Christopher Nolan” );
$titles = array( “Aliens”, “The Big Lebowski”, “Inception” );
$years = array( 1986, 1998, 1973 );

array_multisort( $directors, $titles, $years );

print_r( $directors );
echo “<br />”;
print_r( $titles );
echo “<br />”;
print_r( $years );
echo “<br />”;

Outputs:

Array ( [0] => Christopher Nolan [1] => Ethan Cohen [2] => James Cameron )
Array ( [0] => Inception [1] => The Big Lebowski [2] => Aliens )
Array ( [0] => 2010 [1] => 1998 [2] => 1986 )

Notice how the array_multisort() function has sorted the values in $directors in ascending order and then sorted the other 2 arrays so that the element order matches the order of the sorted $directors array.

Sorting multidimensional arrays

If you pass a multidimensional array to array_multisort() then it sorts by looking at the first element of each nested array.

If 2 elements have the same value then it sorts by the second element, and so on. For example:

$movies = array(
array(
“director” => “Ethan Cohen”,
“title” => “The Big Lebowski”,
“year” => 1998
),
array(
“director” => “James Cameron”,
“title” => “Aliens”,
“year” => 1986
),
array(
“director” => “Christopher Nolan”,
“title” => “Inception”,
“year” => 1973
),
array(
“director” => “James Cameron”,
“title” => “Titanic”,
“year” => 1997
)
);

array_multisort( $movies );
echo “<pre>”;
print_r( $movies );
echo “</pre>”;

Outputs:

Array
(

[0] => Array
(
[director] => Christopher Nolan
[title] => Inception
[year] => 1973
)
[1] => Array
(
[director] => Ethan Cohen
[title] => The Big Lebowski
[year] => 1998
)

[2] => Array
(
[director] => James Cameron
[title] => Aliens
[year] => 1986
)

[3] => Array
(
[director] => James Cameron
[title] => Titanic
[year] => 1997
)
)

So as you can see the array sorting functions in PHP are quite powerful and flexible. This brief post only covers a few options, there are more functions if you require them. Here is a great place to start.

Everything about UTF-8

Filed under PHP, but obviously much more than that.

In an update to this post, it is time for a revisit of UTF-8.

In a post entitled “Everything you always wanted to know about UTF-8 (but never dared to ask)” the good folk at the iBuildings TechPortal have Juliette Reinders Folmer speak on a variety of topics.

“…In this talk I will cover UTF-8 from basic linguistics, through client-side aspects to all the steps you need to take to tackle the most common (and some more obscure) issues when using UTF-8 in a database driven PHP application…”

Check it out here.

Simple PHP Best Practices

This post is intended to make you think a little bit more about some of the habits you may have formed whilst programming. It is not the nirvana of programming, nor best practice, just a few little ideas to help you along the way.

1. Use descriptive variable names
Arguably this is the hallmark of the inexperienced or just plain poor programmer. Using variables names such as $x or $y makes a major sacrifice in readability for a negligible performance improvement.
Remember, variable names are cheap whilst programmer time is not.

2. No commented out code
Sure, commenting out code makes sense if you do not use a revision control system (like CVS/SVN/Git/etc) however, – why on earth are you not using a revision control system?
Leaving commented code behind tends to clutter files and reduces readability, – especially in those hard times on a console and don’t have the luxury of an editor with syntax highlighting and large resolution.

3. Write control structures as you would say them
It is all too easy to make control structures (if, switch, while, etc…) unreadable. An easy trick to improve readability is to read it to yourself, from start to finish; this forces you to read it anew and clears up strange comparisons such as: ‘!$security_check===false’.

4. Use single quotes (‘) by default and double quotes only when you want to put variables in your string
It’s the little things…

Is PHP Agile?

A client recently asked if PHP was an Agile programming language, and during the (rather lengthy) explanation a few principles worth exploring were covered:

In the context of software development Agile is really no more than a set of principles and values. At a meeting in February 2001 people who were then developing software differently to traditional processes drew up a manifesto; they formalised practices favouring constant feedback and change, flat hierachy, and delivered early and often.

PHP is generally considered a lightweight language, – often it is used because it can get things done quicker than with other languages. A language is never agile because it does not generally define the processes used when developing with it. However it can have qualities that can make its development quicker; PHP is light, interpreted, and it is simple. Unfortunately these reasons have also attracted people unconcerned with best practices in order to ‘just get their sites up and running’

Agile doesnt mean doing the job quickly, – dont expect to finish the project earlier, but you will deliver earlier. A part of the system that is testable, usable, and something that adds value. From the feedback the team and customer will decide what will be delivered next. The iterations are closer together than other approaches and in order to deliver quickly you will only deliver what you need.

As far as web application development is concerned, being an interpreted, lightweight, embeddable, simple language, with fairly reasonable object oriented support, PHP is in a fairly unique position to fulfill the needs of agile development teams. The elements are available, but of course it is up to the enterprises to take the step and use what is there for setting up their own agile development environment.