PDA

View Full Version : php timeout


Jack Norton
10-10-2006, 02:36 AM
Hello, tecnical php question :) I have a script that checks if a file is present in one of my mirror:
<?php
function url_exists($url)
{
$handle = @fopen($url, "r");
if ($handle === false)
return false;
fclose($handle);
return true;
}
?>
so I can check, for example, if a demo exist and download it when user click on download (in case one server goes down I can choose another instead of displaying a bad "timeout" page!).
My problem is that is quite slow - takes even 4-5 seconds before giving a response. Was wondering if there's a way to speed up things in php! like check if file exist and if the other server doesn't give any response after 1 second, mark it as timeout/failed and goes to next one :)

EDIT: OK found the solution, sorry! was enough to put this line:
$old = ini_set('default_socket_timeout', $timeout);

jankoM
10-10-2006, 04:08 AM
You can use stream_set_timeout() with fsockopen or fopen (if you have newer php I think). This is example from php docs.

<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
echo "Unable to open\n";
} else {

fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
stream_set_timeout($fp, 2);
$res = fread($fp, 2000);

$info = stream_get_meta_data($fp);
fclose($fp);

if ($info['timed_out']) {
echo 'Connection timed out!';
} else {
echo $res;
}

}
?>

Althougth you should make HEAD request not GET because in your case (few MB) you don't want to download the whole file just to see if it is there. So it's also not so strange that it takes 4 seconds right now.

Jack Norton
10-10-2006, 04:30 AM
Althougth you should make HEAD request not GET because in your case (few MB) you don't want to download the whole file just to see if it is there. So it's also not so strange that it takes 4 seconds right now.

With my previous method, using only fopen() I should just check if file can be opened (without actually reading any data). Correct me if I'm wrong please :) but in the php manual I see they say about fopen($url,"r") that opens the resource and position it at beginning of file (without reading the whole 10mb data).
I hope I'm not reading everytime the whole file just using fopen!! that would be very bad :D

Backov
10-10-2006, 08:48 AM
I would use CURL instead of the fopen command. You get much finer control and you don't run into problems. Check it out, you'll never use fopen for URL stuff again.