PHP:脚本结束后发送HTTP头部的简易方法PHP - simple way to send HTTP headers before a script ends
文章介绍了一种在PHP脚本执行完毕后仍能发送HTTP头部(如重定向)的技术方案,解决了传统header()函数因脚本继续执行导致头部失效的问题,适用于需立即响应后仍进行后台操作的场景。
Terence Eden
Suppose you want PHP to keep processing after it has sent back an HTTP response. Normally, this doesn't work:
<?php
header( "Location: https://example.com/" );
// Long operation.
sleep(10);
die();Try it yourself. You'll have to wait 10 seconds before you get back
< HTTP/2 302
< location: https://example.com/There are some complex ways to fix this - they usually involve spawning sub-processes or having a cron job run something. But there's a simpler way!
Most servers do some form of output buffering. They wait for the buffer to fill (or be explicitly terminated) before they send any content. My server was set to a buffer of 4,096 bytes. So I forced some dummy output to fill it up, then told PHP to flush the buffer:
<?php
header( "Location: https://example.com/" );
echo str_repeat("😆", 4097);
flush();
sleep(10);
die();Some clients, like Python's Requests, wait until they've explicitly seen the end of the response before processing it.
But, for something like curl, the above is sufficient.
需要完整排版与评论请前往来源站点阅读。