doujinge9648 2014-01-27 09:18
浏览 76
已采纳

php-function fsockopen()不起作用

I just started to study php and I'm reading about fsockopen(). I tried to repeat an example from the book, but as result I get an empty page without any information.

<?php
function get_content ($hostname, $path)
{
    $line = "";
    $fp = fsockopen($hostname, 80, $errno, $errstr, 30);
    if(!$fp) echo "$errstr ($errno)<br />
";
    else 
    {
        $headers = "GET $path HTTP/1.0
";
        $headers .= "Host: $hostname
";
        $headers .= "Connection: Close

";
        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);
}
?>

What's wrong with this code and why it doesn't work?

  • 写回答

1条回答 默认 最新

  • duanbei3747 2014-01-27 09:22
    关注

    Lines after the return statements will never be reached.

    You may want to get the last three lines of your function, out of the function.

    function get_content($hostname, $path) {
        $line = "";
        $fp   = fsockopen($hostname, 80, $errno, $errstr, 30);
        if (!$fp) echo "$errstr ($errno)<br />
    ";
        else {
            $headers = "GET $path HTTP/1.0
    ";
            $headers .= "Host: $hostname
    ";
            $headers .= "Connection: Close
    
    ";
            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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来