views:

69

answers:

2

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

$sql = "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?

+1  A: 

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.

Col. Shrapnel
just trying to make the visitors wait for the redirect as short as possible.
Mark
@Mark how long do they have to wait? a half-hour?
Col. Shrapnel
every second counts when your trying to make a sale.
Mark
@Mark a **whole second?** are you run you server on IBM XT?
Col. Shrapnel
@Col. Shrapnel Sorry, that should of read every "fraction" of a second counts when your trying to make a sale.
Mark
+4  A: 

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.

Wrikken
looks like last one is one the OP asks
Col. Shrapnel
Surely `ignore_user_abort()` should be before `header()`?
Hammerite
@Hammerite: added some background to the answer.
Wrikken