Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
828 views
in Technique[技术] by (71.8m points)

file get contents - PHP file_get_contents ignoring timeout?

$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, "
";

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...