douling0053 2010-09-19 20:28
浏览 36
已采纳

在执行PHP脚本的其余部分之前,header()重定向是否可以进行

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?

  • 写回答

2条回答 默认 最新

  • douwen5985 2010-09-19 20:31
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳