我在ubuntu服务器(nginx php5-fpm堆栈)上有一个奇怪的行为,代码解释了问题:
<?php
// WORKS:
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
// DOES NOT WORK! Return empty string (no error like NULL or False whatsoever).
echo file_get_contents("http://www.example.com");
// allow_ftp_open is On
echo var_dump(ini_get('allow_url_fopen')); // returns '1'
?>
使用fopen代码:
<?php
// get contents of a file into a string
$filename = "http://www.example.com";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
echo $contents;
?>
生成这个:
Warning: filesize(): stat failed for http://www.example.com in test.php on line 5
Warning: fread(): Length parameter must be greater than 0 in test.php on line 5
如果我在fread中使用固定大小,结果是一个空字符串,就像使用file_get_contents一样。
套接字如何工作正常,但fopen不行?我错过了什么?
答案 0 :(得分:0)
当从非常规本地文件读取任何内容时,读取将在数据包可用后停止。试试这样的事情
if ($fp = fopen('http://www.example.com/', 'r')) {
$contents = '';
while ($line = fread($fp, 1024)) {
$contents.= $line;
}
}