There is many ways to optimize or cache, the best way depends on what you are trying to cache, the quantity and the desired refresh frequency. Examples are
- store calculated result in session, a database or file - then look it up
- do calculations upfront, lookup them up then needed
- store your pages (PHP output in files) and deliver stored versions to users
- use a cache / HTTP-accelerator like Varnish.
In this case, I think an upfront calculation would satisfy your needs. Simply put your code in a single script, calculate.php, that saves the calculated $total_pages
value to a file :
<?
$memefiles = glob("usermemes/*.jpeg");
$total_pages = ceil(sizeof($memefiles)/$num_rec_per_page);
file_put_contents('totalpages.dat', $total_pages);
?>
Now setup a cron job, running calcaulate.php
every 1 minute, 5 minutes, every hour or what your needs is. If you are running on a windows server, you should use the Task Scheduler equivalence instead. Setting up cronjobs is very easy, but it vary between systems and GUI / commandline tools, there is difference if you have a on-site server or are using a professional webhost. So search stackoverflow for cron jobs suiting your particular situation.
Assuming you have a cron job up running, saving the value of $total_pages
to a file, then you are retrieving your value on the webpage by
$total_pages = file_get_contents('totalpages.dat');
This will by guarantee boost the performance of all pages in need of delivering the $total_pages
value. Compared to the accepted answer, this solution has some significant advantages :
- the task is runned only once, each time, no matter if you have 1, 10.000 or 1.000.000 users / pageloads.
- users can still receive nearly fresh or almost live data. How fresh is determined by the cronjob frequency.