我刚刚开始研究php,我正在阅读fsockopen()
。我试图从书中重复一个例子,但结果我得到一个没有任何信息的空页。
<?php
function get_content ($hostname, $path)
{
$line = "";
$fp = fsockopen($hostname, 80, $errno, $errstr, 30);
if(!$fp) echo "$errstr ($errno)<br />\n";
else
{
$headers = "GET $path HTTP/1.0\r\n";
$headers .= "Host: $hostname\r\n";
$headers .= "Connection: Close\r\n\r\n";
fwrite($fp, $headers);
while (!feof($fp))
{
$line .= fgets($fp, 1024);
}
fclose ($fp);
}
return $line;
$hostname = "www.php.net";
$path = "/index.php";
//set_time_limit(180);
echo get_content ($hostname, $path);
}
?>
此代码有什么问题以及为什么它不起作用?
答案 0 :(得分:3)
永远不会到达return
语句之后的行。
您可能希望从函数中获取函数的最后三行。
function get_content($hostname, $path) {
$line = "";
$fp = fsockopen($hostname, 80, $errno, $errstr, 30);
if (!$fp) echo "$errstr ($errno)<br />\n";
else {
$headers = "GET $path HTTP/1.0\r\n";
$headers .= "Host: $hostname\r\n";
$headers .= "Connection: Close\r\n\r\n";
fwrite($fp, $headers);
while (!feof($fp)) {
$line .= fgets($fp, 1024);
}
fclose($fp);
}
return $line;
}
//Outside the function!
$hostname = "www.php.net";
$path = "/index.php";
//set_time_limit(180);
echo get_content($hostname, $path);