开发者

Can a header() redirect go before the rest of the PHP script executes

I'm writing a redirect script in PHP that will insert info about the click in a MySQL database.

Will it always insert the info if the database if I put the header() function before the insert? I want to do it this way to make the redirect as fast as possible.

$location = "Location: http://www.example.com";
header($location);

$s开发者_开发知识库ql = "INSERT INTO tracking (info) VALUES ('$info')";
$result = @mysql_query($sql, $con) or die(mysql_error());

I have tested it and it does insert the info in the database. However, my main concern is if the server is running slow and the header() function completes before the insert takes place will the script end without inserting the info in the database.

Or will the script complete regardless?


If you want nothing to run:

header('..');
exit;

If you want to be reasonably sure the rest runs:

header('..');
ignore_user_abort(true);

Actually, 301's & 302's can contain a body according to the HTTP definition (the phrasing is "Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).") and indeed if your browser supports it, you can just (temporarily) disable redirects and watch the actual page being rendered. Whether the browser will follow a redirect immediately after a header, or wait for it's entire request to finish, is up to the user-agent itself. It will wait for all headers though in my experience (cookie headers for instance), so whether to call it before or after the initial redirect header makes no difference, but make sure you sent it before any content / body.

There are limits to the uses of ignore_session_abort(), the usual timeout of the webserver itself, and disconnects due to settings in the webserver itself, apply. If you have a process that takes a lot of time you should not keep a webserver process busy when it's not doing any HTTP communication. In that case, an asynchronous job system like gearman's might be more what you're looking for.


Yes. Redirect can go before.
No you cannot guarantee it will always insert the info in the database. You cannot rely on this at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜