Image sizes and PHP

If you have the GD extension available, you can do a few useful things. One of the simple things is getting an image size is a simple matter. You can either fetch the height and width in seperate variables – or even fetch the height and width in a string pre-formatted for use in an image tag.

Here’s the example in source:

$load\_ext = get\_loaded\_extensions();

if (!in\_array(gd, $load\_ext)) {
    echo "GD is NOT available";
    die();
}

$nikonFile   = './aarhus\_demo\_photo.jpg';
list($width, $height, $type, $img\_txt)  = getimagesize($nikonFile);

echo "The image is ".$width . " by ".$height."\\n";
echo "![]($nikonFile)\\n";

Reading Exif data with PHP

Within most photos from digital cameras besides the actual image, there’s a little ”information block” call EXIF data. If you have the correct PHP extension installed on your server – the one called ”exif” – it’s pretty easy to read the EXIF data and display them, as you like.

First, let’s check if the extension is available?

$load\_ext = get\_loaded\_extensions();
if (!in\_array(exif, $load\_ext)) {
echo "Exif is NOT available";
} else {
echo "Exif extension is available.";
};

Simple benchmarks in PHP

If you’re doing some basic profiling of your PHP scripts, the build-in microtime function can help you make some simple benchmarking fast. Here’s a rough example to show you how it could be used. The doSomething function is the function we want to benchmark.

$time = microtime();
$time = explode(' ', $time);
$time = $time\[1\] + $time\[0\];
$start = $time;

doSomething();

$time = microtime();
$time = explode(' ', $time);
$time = $time\[1\] + $time\[0\];
$finish = $time;
$total\_time = round(($finish - $start), 6);
if ($debug) print ("<p>Processing took approximately $total\_time seconds</p>");

Create a random password with PHP

Some websites require access control, and sometimes you may need to generate a password for a user. Here’s a simple function that can do just that.

The $base-variable contains the characters allowed in the password. The supplied string may be changed, but the selected charaters should exist on all keyboards (as far as I know). When calling the function, you can specify the lenght of the password you want. Simple, right?

function makePassword($desiredLenght = 8) {
    $password = '';
    $base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

    for($i=0;$i<$desiredLenght;$i++) {
        $password .= $base\[(rand(0, (strlen($base)-1)))\];
    }
    return $password;
}

Cracking the Cryptex with PHP

In the book “the Davinci Code” there was a fun little device called a cryptex.. A Cryptex has 6 dials with 6  letters on each, and only one combination producing a word will open it. The most straight forward way to crack it would be to try every combination one by one, but there’s a substantial number of combinations and we know only those which a valid words is a candidate.