猿问

php feof 特别慢

class Socket
{
    protected $crlf = "\r\n";

    protected $host = '';

    protected $port = 80;
    
    protected $method = 'GET';

    protected $path = '/';
    
    protected $httpVersion = 'HTTP/1.1';

    protected $headers = array();

    protected $body = '';

    protected $error = array();

    protected $timeout = 5;

    public function url($url)
    {
        $info = parse_url($url);
        $this->host = $info['host'];
        isset($info['path']) && $this->path = $info['path'];
        isset($info['port']) && $this->port = $info['port'];

        return $this;
    }

    public function method($method)
    {
        $this->method = $method;

        return $this;
    }

    public function path($path)
    {
        $this->path = $path;

        return $this;
    }

    public function httpVersion($version)
    {
        $this->httpVersion = $version;

        return $this;
    }

    public function host($host)
    {
        $this->host = $host;

        return $this;
    }

    public function header($header)
    {
        $this->headers[] = $header;

        return $this;
    }

    public function body($body)
    {
        $this->body = $body;

        return $this;
    }

    public function send()
    {
        $handle = fsockopen($this->host, $this->port, $this->error['errno'], $this->error['errstr'], $this->timeout);

        $req = join($this->crlf, array_merge( array("{$this->method} {$this->path} {$this->httpVersion}"), array("Host: {$this->host}"), $this->headers, array(''), array($this->body), array('') ));

        fwrite($handle, $req);

        $res = '';
        
        while ( !feof($handle) ) {
            $res .= fread($handle, 1024);
        }

        fclose($handle);

        return $res;
    }

}

$s = new Socket();

var_dump( $s->url('http://baidu.com')->send() );

send()方法里的while特别慢,如果只是调用fread($handle, 1024),速度很快,朋友们看看什么情况啊?

慕妹3242003
浏览 425回答 1
1回答

慕丝7291255

这个!feof($handle) 条件 一直成立 所以一直在循环 所以慢,你单独调用fread($handle, 1024) 只执行一次当然快
随时随地看视频慕课网APP
我要回答