views:

45

answers:

2
$url = 'http://a.url/i-know-is-down';

//ini_set('default_socket_timeout', 5);

$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 5,
        'ignore_errors' => true
        )
    )
);

$start = microtime(true);
$content = @file_get_contents($url, false, $ctx);
$end = microtime(true);
echo $end - $start, "\n";

the response I get is generally 21.232 segs, shouldn't be about five seconds???

Uncommenting the ini_set line don't help at all.

A: 

http://php.net/manual/en/function.file-get-contents.php

One of the comments:

Setting the timeout properly without messing with ini values:

<?php
$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
        )
    )
);
file_get_contents("http://example.com/", 0, $ctx);
?>
Tomasz Kowalczyk
@Tomasz Kowalczyk: did you read my post? That's *exactly* how I'm doing it.
Cesar
I've quickly scanned code in your post, sorry, didn't see that it was the same. But it is also the way I do this, and it works, so...
Tomasz Kowalczyk
A: 

You are setting the read timeout with socket_create_context. If the page you are trying to access doesn't exist then the server will let you connect and give you a 404. However, if the site doesn't exist (won't resolve or no web server behind it), then file_get_contents() will ignore read timeout because it hasn't even timed out connecting to it yet.

I don't think you can set the connection timeout in file_get_contents. I recently rewrote some code to use fsockopen() exactly because it lets you specify connect timeout

$connTimeout = 30 ;
$fp = fsockopen($hostname, $port, $errno, $errstr, $connTimeout);

Ofcourse going to fsockopen will require you to then fread() from it in a loop, compicating your code slightly. It does give you more control, however, on detecting read timeouts while reading from it using stream_get_meta_data()

http://php.net/stream_get_meta_data

Fanis