PHP

Use cURL to obtain remote filesize


Sometimes you might want to determine a remote file size prior to determining further action to take. This is a quick function that utilises cURL to retrieve the file size in bytes.
<?php
function remoteFilesize ($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$info = curl_exec($ch);
curl_close($ch);
$info = explode('Content-Length:', $info);
$info = explode("Connection",$info[1]);
return $info[0];
}
?>

Usage is simple:

echo remoteFilesize("test.com/file.html");

Use cURL to obtain remote filesize Read More »

Get Facebook Likes and Shares via Graph API


Facebook Like and Share count can easily be obtained from the Facebook Graph API. This is an extremely quick way to look up the JSON response from Facebook so that you can further process it for your own requirements.
<?php
$URL ='https://graph.facebook.com/cocacola';
$JSON = file_get_contents($URL);
$Output = json_decode($JSON);
$Likes = 0;
if($Output->likes){
  $Likes = $Output->likes;
}

echo "Number of likes for CocaCola's Facebook Page = ".$Likes."</br>";

$URL2 ='https://graph.facebook.com/http://www.coca-cola.com';
$JSON2 = file_get_contents($URL2);
$Output2 = json_decode($JSON2);
$Shares = 0;
if($Output2->shares){
  $Shares = $Output2->shares;
}

echo "Number of shares for coca-cola.com = ".$Shares;
?>

UPDATE 29/01/2012: I’ve written a slightly different method using the PHP SDK in this post here

Get Facebook Likes and Shares via Graph API Read More »

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);

Currency Conversion using Yahoo Finance API Read More »

PHP Script Execution Timer Class

< Often for testing the efficiency 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();

PHP Script Execution Timer Class Read More »

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.

cURL in PHP to access protected sites Read More »

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';
}
}

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

PHP URL Shortening Read More »

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.

PHP Arrays Read More »

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.

Everything about UTF-8 Read More »