Have you ever wondered how some web sites show a “loaded in x seconds” or “page created in x seconds” in the footer? Well, it’s a simple PHP script to add.

Add the following code snippet in the page head. For more accurate results, place it above the <!DOCTYPE> declaration:

<!-- put this at the top of the page -->
<?php
$mtime = microtime();
$mtime = explode(' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime
?>

Then, add the following code snippet where you want your timer to show up (usually in the footer):

<!-- put this code at the bottom of the page -->
<?php
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo 'This page was created in '.$totaltime.' seconds.';
?>

PHP’s microtime() function returns the current Unix timestamp with microseconds. And the explode() function returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

Another implementation, this time having an option for how many decimals to show:

<!-- put this at the top of the page -->
<?php
$mic_time = explode(" ",microtime());
$mic_time = $mic_time[1] + $mic_time[0];
$starttime = $mic_time;
?>

<!-- put this code at the bottom of the page -->
<?php
$places = 5; // How many decimal want to show
$mic_time = explode(" ",microtime());
$mic_time = $mic_time[1] + $mic_time[0];
$finishtime = $mic_time;
echo "Page loaded in ".round(($finishtime - $starttime),$places)." seconds";
?>

One Response to How To Add A "Page loaded in…" Feature

  • Thanks for the tutorial. I like php a lot…

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>