Have you ever noticed that lots of websites feature some text towards the very bottom of a page saying “Page took x.xxx seconds to load”? It’s a pretty simple thing to make and gives your site something that we all love … stats! So today we’ll take a look at how to accomplish this through the use of PHP. First off let’s outline what we’ll need to do for this:
- Get the time in micro-seconds using the function: microtime().
- Turn the micro-time into an array using the explode() function.
- Add the two parts of the array together (the micro-seconds to the seconds).
- Repeat steps 1,2 and 3 for the bottom of the page.
- Find the total loading time by taking the time taken at the end of the page from the time taken at the top of the page.
- Round the microtime and return it to the browser.
So we start with measuring the time at the top of the page – so right after you’re opening <HTML> tag go ahead and insert the following code:
<? $m_time = explode(" ",microtime()); $m_time = $m_time[0] + $m_time[1]; $starttime = $m_time; ?>
We have now completed the first 3 steps – and stored the starting time into a variable called starttime. Now we just need to repeat these 3 steps at the very bottom of the page, compare the 2 times, and echo out our display to the browser. So place the following at the bottom of the page where you wish to display the loading time:
<? $round = 3;// The number of decimal places to round the micro time to. $m_time = explode(" ",microtime()); $m_time = $m_time[0] + $m_time[1]; $endtime = $m_time; $totaltime = ($endtime - $starttime); echo "Page loading took:". round($totaltime,$round) ." seconds"; ?>