3

I created a PHP file in which a map is drawn with GD based on data obtained from another site. The fact is that the PHP run-time makes the page loading is very slow.

The question is, is there any way this PHP code is executed only once a day? o any chance you run the web server automatically?

Bcl00
  • 207
  • 3
  • 15
  • You can use windows task scheduler to run the php file once a day. http://stackoverflow.com/questions/295386/how-to-run-a-php-file-in-a-scheduled-task – Jason Fuller Aug 04 '11 at 20:06

3 Answers3

2

You need to cache your map image and load it from a file if it already exists. Regenerate it once a day. This skeletal code outlines how that can be accomplished. The first time the page loads when the image has become more than a day old, it will be regenerated and saved to a file.

// If the file is older than 1 day, create a new one
if (filemtime("imagecache.jpg") < time() - 86400) {

  // Generate your new image and write it to a file
  // Assuming $im is an image from GD

  // UPDATE: fixed file_put_contents() because I didn't know imagejpeg() 
  // could write the file by itself.
  imagejpeg($im, "imagecache.jpg");
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • I really like this solution... no need for external scripts on a schedule. Nice! – Problematic Aug 04 '11 at 20:10
  • Me too! Only problem I can see is that the lucky first user to hit the page after the image expires will run into the problems @Bcl00 talks about, namely, slow loading as GD crunches. – Problematic Aug 04 '11 at 20:12
1

Many ways to do this. They all start with having a PHP script that creates a static graphic file using gd and saves it somewhere in the disk. This is what you will show to users.

Once you're generating that file your two easiest choices might be:

  1. Point your users to the static file, and invoke the php periodically using cron or something similar.
  2. Point your users to a PHP script. Have your PHP script check the graphic file's timestamp and if it's older than a certain age, regenerate it and then send that to the user. Thus you have some PHP overhead but it's less than generating the graphic every time.
Roadmaster
  • 5,297
  • 1
  • 23
  • 21
0

Create a cron job that runs once a day (preferably during a light traffic time) to do your heavy lifting, save or cache the result (for example, using APC or memcached, or even just overwriting the currently-used image with the new one), and display that result to your users.

Problematic
  • 17,567
  • 10
  • 73
  • 85