PHP请求URL而不等待响应

5
我想要做一个类似于file_get_content的变体,但是不需要等待内容。基本上我正在请求一个不同url中的另一个php脚本来下载一个大文件,所以我不想等待文件完成加载。有没有人有什么想法?
谢谢!

1
你看过这个 https://dev59.com/rHVD5IYBdhLWcg3wAGeD 吗? - Asif Mulla
3个回答

2
我建议您查看popen函数或curl multi函数。
最简单的方法是:
$fh = popen("php /path/to/my/script.php");

// Do other stuff

// Wait for script to finish
while (fgets($fh) !== false) {}

// Close the file handle
pclose($fh);

如果您根本不想等待它完成:

exec("php /path/to/my/script.php >> /dev/null &");

或者

exec("wget http//www.example.com/myscript.php");

我曾经使用过wget变体,但它需要相当多的资源。它可以轻松地花费0.1秒甚至更长时间来处理,如果您需要定期在公开的网页上执行此操作,则非常糟糕。 - Josef Sábl

2

在将下载该文件的脚本运行之前,请尝试以下操作:

//Erase the output buffer
ob_end_clean();
//Tell the browser that the connection's closed
header("Connection: close");

//Ignore the user's abort.
ignore_user_abort(true);

//Extend time limit to 30 minutes
set_time_limit(1800);
//Extend memory limit to 10MB
ini_set("memory_limit","10M");
//Start output buffering again
ob_start();

//Tell the browser we're serious... there's really
//nothing else to receive from this page.
header("Content-Length: 0");

//Send the output buffer and turn output buffering off.
ob_end_flush();
//Yes... flush again.
flush();

//Close the session.
session_write_close();

// Download script goes here !!!

来源: http://andrewensley.com/2009/06/php-redirect-and-continue-without-abort/

在PHP中,如果您想重定向到另一个页面并且希望脚本继续执行而不是立即停止,可以使用以下代码:
```php header('Location: http://www.example.com/'); flush(); // 继续执行剩余的PHP代码 ```
这样做的原因是当您调用header()函数时,它会发送一个HTTP头并将脚本停止。但是,如果您在调用header()函数之后立即调用flush()函数,则可以将缓冲区中的所有输出发送到浏览器并继续执行剩余的PHP代码。请注意,此方法仅适用于使用输出缓冲的情况。

你应该尽可能在脚本的开头使用session_write_close(),否则即使用户已经在他们的端口中断了下载,这个脚本仍会锁定会话直到下载完成。 - Marc B
这段代码应该是文件中的第一段。其余的内容(下载脚本等)应该在它之后。在这个例子中,这个位置被标记为“// 下载脚本放在这里”。 - s3v3n
1
这是对特定问题的好答案,但并没有解决问题本身。我需要类似的东西,但我无法控制第二个脚本,所以对我没用。 - Josef Sábl

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接