ipel
ipel

Reputation: 1346

How to limit the max execution time of a PHP script

I have a php script (file.php) that is used to counts banner impressions and returns an image, it end like this:

readfile('http://somedomain.com/banner.jpg');
mysql_close();
exit;

This file is used very much, and sometimes when the image is hosted on external server it load slow.

So to reduce my hosting usage i think to add a max execution time only on this script, for example: if 5-10 seconds are passed, the script closes

i think that is possibile, but how?

Upvotes: 1

Views: 374

Answers (3)

VolkerK
VolkerK

Reputation: 96189

I just tested set_time_limit() but apparently readfile('http...'); doesn't honor this setting. The script was executed longer than the amount of time set via set_time_limit, but then aborted before the next "in-script" statment was executed.
But since php 5.2.1 the http url wrapper has a context option timeout which seems to do the trick.

mysql_close();
$ctx = stream_context_create( array(
    'http' => array(
        'timeout'  => 4.7 // in seconds
    )
);
readfile('http://somedomain.com/banner.jpg', false, $ctx);
exit;

see http://docs.php.net/context.http

Upvotes: 2

Matthew Thomas
Matthew Thomas

Reputation: 36

Change you max_execution_time in you php.ini or add to your script ini_set('max_execution_time', 5);

Upvotes: 0

René Höhle
René Höhle

Reputation: 27325

You can set the execution time on the top of your script with the set-time-limit function.

Upvotes: 1

Related Questions