PHP Snippets

Here are some PHP snippets. Feel free to take and use whatever you want!

Intro

  1. Counting the generation time of a page
  2. Convert an image into Base64 code
  3. Create a HTML calender using PHP
  4. Safely delete a file using PHP
  5. Remove the alpha layer of a PNG using GD and PHP

Counting the generation time of a page

This code monitors the time used by PHP to generate a page, without JavaScript.

Warning: only the generation time is monitored. Neither the DNS records nor the download delay are taken in account here.

<?php
    $time = microtime();          // Actual timestamp
    $time = explode(' ', $time);  // separate integer and fractional part of time
    $begin = $time[0]+$time[1];   // Needed to get "0.000025 sec" instead of "2.5E-5 sec" format

// YOUR CODE HERE

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

    echo round(($end - $begin),6).' seconds';
?>

With PHP 5, it’s even simplier :

<?php
    $begin = microtime(TRUE);

// YOUR CODE HERE

    $end = microtime(TRUE);
    echo round(($end - $begin),6).' seconds';
?>

Top

Convert an image into Base64 code

Base64 is the textual representation (in ASCII caracters) of a binary file, like an image. Some protocols don't allow file transferts. One can in these cases make use of the Base64 representation of the file, to send them anyway, in a textual format.

The following functions can be useful for that: the first reads an image and converts it into BASE64 code. The secondth does the oposite: it turns the BASE64 code of an actual image into that image, that file.

<?php

// converting an image into BASE64

function file2base64($source) {
    $bin_data_source = fread(fopen($source, "r"), filesize($source)); // reading as binary string
    $b64_data_source = base64_encode($bin_data_source);               // BASE64 encodage
    return $b64_data_source;
}	


// creating an image from BASE64 code

function base642file($b64_data_target, $image_target_name) {
    $bin_data_target = base64_decode($b64_data_target);        // base64 decodage
    $image_target = fopen($image_target_name, 'wb');           // Create a file
    if (fwrite($image_target, $bin_data_target))               // Write the file
        return TRUE;
    else
        return FALSE;
}

$source = 'image.png';
$base64_data = file2base64($source);

//

$data64 = 'iVBORw0KGgoAAAANSU [ … / … ] FTkSuQmCC';
base642file($data64, 'destination.png');

?>

This method :

Sommaire

Create a HTML calender using PHP

This creates a month calendar in HTML:

<?php

function print_calendrier() {
    $current_month_letters = date('F');
    $week_days = array('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su');

    $first_day = mktime('0', '0', '0', date('m'), '1', date('Y'));

    // table caption
    $calendar = '<table id="calendar">'."\n";
    $calendar.= '<caption>'.$current_month_letters.'</caption>'."\n";
    $calendar.= '<tr><th>'.implode('</th><th>', $week_days).'</th></tr><tr>';

    // a month doesn’t necessarely begin on a monday
    $day_offset = date('w', $first_day-'1');
    if ($day_offset > 0) {
        for ($i = 0; $i < $day_offset; $i++) {
            $calendar.=  '<td></td>';
        }
    }

    // generating table
    for ($day = 1; $day <= date('t'); $day++) {
        $calendar.= '<td';

        // adds a CSS class on “today” cell
        $calendar .= ($day == date('d')) ? ' class="active"' : '';

        $calendar.= '>';
        $calendar.= $day;
        $calendar.= '</td>';
        $day_offset++;
        if ($day_offset == '7') {
            $day_offset = '0';
            $calendar.=  '</tr>'."\n";
            $calendar.= ($day < date('t')) ? '<tr>' : '';
        }
    }

    // Complets the last row with empty cells at the end
    if ($day_offset > '0') {
        for ($i = $day_offset; $i < '7'; $i++) {
            $calendar.= '<td></td>';
        }
        $calendar.= '</tr>'."\n";
    }
    $calendar.= '</table>'."\n";

    return $calendar;
}

?>

The calendar has the CSS ID "calendrier" ; current date has the CSS class "active".

Sommaire

Safely delete a file using PHP

In order to remove a file using PHP, one has to pay attention. Once again :never trust user input.

The problem

Consider this code :

$folder = 'sub_folder/';
$file = $_GET['file_name'];

if (TRUE === unlink($folder.$file)) echo 'File deleted';

This works perfectly: the file name given in the URL parameter is removed.
Is I go here: http://mysite/page.php?file_name=image.jpg, the file /sub_folder/image.jpg will be removed. Good.

Well, let’s imagine an user goes here : http://mysite/page.php?fiel_name=../page.php. You see? The removed file will be /sub_folder/../page.php, in other words /page.php !!!

This is not acceptable: any file can be removed using this way, including importants files or even whole folders…

One solution.

We have to assume that out hosted fils are in one specific folder (the files in all the other folders cannot be removed). Example, if we are considering the user images, they are in the subfolder "/image".
What we do, is list the files in that directory, and compare these files with the one that is in the URL, in the $_GET. If there is a match, the file can be removed, otherwise, nothing is done.

    $folder = 'sub_folder';
    $list = scandir($folder); // listing files
    $file = $_GET['file_name'];

    $nb_fichier = count($list);
    for ($i = 0 ; $i < $nb_files ; $i++) {
        if ($list[$i] == $file and !($list[$i] == '..' or $list[$i] == '.')) {
            if (TRUE === unlink($folder.$list[$i])) echo 'file deleted';
        }
    }

Here, I even add the condition the file cannot be "." nor ".." (the folder itself, or the parent folder)

Of course, in you script, you have to add the useual "htmlspecialchars()" and other tests.

Sommaire

Removing the alpha layer of a PNG using GD and PHP

I spend some hours trying to get rid of the transparency in some PNG images that I needed to get thumbnailed, in JPG. The problem was that I sometimes get my images black instead of white… And with some scripts I font on the web, the transparency get white in some images, but not in all.

Here I found something that works nicely. It works even if you use "imagejpeg" or "imagepng" at the end.

$image = 'my-png-with-transparency-image.png';

function remove_alpha($Source) {

    $Dest = 'destination.jpg';
    // width and heigt
    list($width, $height) = getimagesize($Source);

    // Create a destination image ressource
    $IMG_dest = imagecreatetruecolor($width, $height);
    // Fill it with white
    imagefill($IMG_dest, 0, 0, imagecolorallocate($IMG_dest, 255, 255, 255));

    // Opens our source PNG file.
    $IMG_source = imagecreatefrompng($Source);

    // Merge our image (with alpha) on the white layer
    // This line is the key
    imagecopy($IMG_dest, $IMG_source, 0, 0, 0, 0, $width, $height);
    imagedestroy($IMG_source);

    // save in JPG, quality 90%
    imagejpeg($IMG_dest, $rDest, 90);
    imagedestroy($IMG_dest);

return $Dest;	
}

echo '<img src="'.remove_alpha($image).'"/>';

Sommaire

Ressources…

Sommaire

Page créée en janvier 2011. Dernière mise à jour le jeudi 15 décembre 2011.
Adresse de la page : http://lehollandaisvolant.net/tuto/php/