在PHP中完成处理后重定向页面 [英] Redirect page after process complete in PHP
问题描述
我在页面中有一些处理.正在下载文件.
I have some process in page. It's downloading a file.
<?php
// getting file with CURL
$ch = curl_init ('http://adress.com/file.csv');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,7500);
$rawdata=curl_exec($ch);
curl_close ($ch);
// End Curl Process
// SAVE FILE
$name = Rand(100000,1000000);
$fp = fopen('files/'.$name.'.csv','w');
fwrite($fp, $rawdata);
fclose($fp);
// END SAVE PROCESS
// REDIRECT OTHER PAGE
**header('Location: x.php');**
// END OF PAGE
?>
没关系.但有一个问题.它重定向而无需完成过程.我想在所有过程完成后进行重定向.当我使用该方法重定向时,该文件为空.
This is allright. But there is a problem. It redirects without complete process. I want to redirect after all processes are done. The file is empty when i redirect with that method.
我该怎么办?完成所有过程后,如何重定向页面? php或javascript/jquery.
What must I do? How can i redirect page after all processes are done? php or javascript/jquery.
推荐答案
您的代码应该没问题,并且应该在重定向之前完成该过程.
Your code should be fine, and should complete the process before redirecting.
PHP在单个线程中运行,因此下一个语句要等到前一个语句完成后才能执行.这意味着,在fwrite()
完成文件写入之前,您的header()
行将不执行.
PHP runs in a single thread, so the next statement won't be executed until the previous one completes. This means that your header()
line won't execute until fwrite()
has finished writing the file.
实际上,设置Location
标头甚至并不意味着PHP脚本停止.您可以通过创建虚拟文件并在发出Location
标头后在其上运行unlink()
来进行测试.该文件仍将被删除. Location
所做的只是向浏览器发送一个新位置.然后,您的浏览器会在旧页面完成运行之前检索新页面.
In fact, setting a Location
header doesn't even mean the PHP script stops. You can test this by creating a dummy file and running unlink()
on it after issuing the Location
header. The file will still be deleted. All that Location
does is sends a new location to your browser. Your browser then retrieves the new page before the old one is done running.
这篇关于在PHP中完成处理后重定向页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!