Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中调用echo时,头从何而来?_Php_Header_Echo - Fatal编程技术网

在PHP中调用echo时,头从何而来?

在PHP中调用echo时,头从何而来?,php,header,echo,Php,Header,Echo,我看到的代码来自PHP手册 $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\

我看到的代码来自PHP手册

$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);
}

http头从哪里来?

您在这段代码中所做的是:

  • 打开到远程HTTP服务器(端口80上的www.example.com)的套接字连接。这将建立到该端口的TCP连接
  • 然后通过此连接发送(通过
    fwrite
    )HTTP请求。HTTP是TCP之上的一个协议,您在这里手动制定HTTP协议头
  • 然后(通过
    fgets
    )读取远程服务器的(HTTP)响应
  • 我猜您想知道为什么在这个远程响应中会看到HTTP头,即使您只是在执行
    echo'hello'。答案是因为在该服务器上运行的web服务器正在处理HTTP事务。您没有在PHP中处理传入HTTP请求的任何细节,也没有处理传出响应的任何细节。运行PHP的web服务器(可能是Apache)正在这样做

    整个堆栈包括一个TCP连接,该连接承载一个HTTP请求,该请求由HTTP头和HTTP正文组成。在服务器上,TCP连接通常由底层操作系统处理,这使得该连接可以作为web服务器的套接字使用,在web服务器上,web服务器“打开”HTTP请求来处理它,并在必要时调用PHP,然后整个链向后返回以获得响应

    echo 'hello';