php – header()如何工作?
一点背景:
我需要在浏览器中运行 PHP脚本,但我不想在安装服务器时遇到麻烦,并且在计算机上运行服务器以及随之而来的所有东西,包括防火墙,等等.等等等等. 所以我编写了自己的服务器.这是一个简单的PHP脚本,它侦听我的局域网IP的端口80上的连接,然后我只是在我的浏览器中加载该IP并且它可以工作.它接收HTTP请求并使用exec启动第二个PHP脚本 – 这样我就可以轻松地对其进行更改而无需重新启动服务器脚本.第二个PHP脚本解析请求,最后包含实际调用的脚本.它从那里获取输出,并使用适当的标头(我可以更改)将响应发送回浏览器. 是的,这是一团糟,但它的确有效.它做我需要做的事情. 现在提问: 我想知道header()函数在内部是如何实际工作的,这样我就可以使用该函数而不是我的“黑客”函数.
CLI SAPI完全忽略header()函数.但它对Apache和CGI SAPI有影响.
简而言之,CLI SAPI没有在sapi _ * _ header_ *函数中实现任何逻辑.例如,对于CLI SAPI,在php_cli.c中: static int sapi_cli_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC) /* {{{ */ { /* We do nothing here,this function is needed to prevent that the fallback * header handling is called. */ return SAPI_HEADER_SENT_SUCCESSFULLY; } /* }}} */ 所有这些函数基本上都返回NULL,0或假成功消息. 对于CGI SAPI,在cgi_main.c中: static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC) { char buf[SAPI_CGI_MAX_HEADER_LENGTH]; sapi_header_struct *h; zend_llist_position pos; zend_bool ignore_status = 0; int response_status = SG(sapi_headers).http_response_code; // Lots of other code... } 你可以使用php-cgi二进制文件和一些数组操作轻松地完成这项工作: server.php $script_to_run = 'script.php'; exec('php-cgi '.escapeshellarg($script_to_run),$output); $separator = array_search("",$output); $headers = array_slice($output,$separator); $body = implode("rn",array_slice($output,$separator+1)); print_r($headers); print $body; script.php的 header('Content-Type: text/plain'); echo 'Hello,World!'; 输出: Array ( [0] => X-Powered-By: PHP/5.3.8 [1] => Content-Type: text/plain ) Hello,World! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |