运行并发 PHP 脚本 [英] Running concurrent PHP scripts

查看:33
本文介绍了运行并发 PHP 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 VPS 服务器出现以下问题.

I'm having the following problem with my VPS server.

我有一个长时间运行的 PHP 脚本,可以将大文件发送到浏览器.它做这样的事情:

I have a long-running PHP script that sends big files to the browser. It does something like this:

<?php
header("Content-type: application/octet-stream");
readfile("really-big-file.zip");
exit();
?>

这基本上是从服务器的文件系统中读取文件并将其发送到浏览器.我不能只使用直接链接(并让 Apache 为文件提供服务),因为应用程序中存在需要应用的业务逻辑.

This basically reads the file from the server's file system and sends it to the browser. I can't just use direct links(and let Apache serve the file) because there is business logic in the application that needs to be applied.

问题在于,当此类下载正在运行时,该站点不响应其他请求.

The problem is that while such download is running, the site doesn't respond to other requests.

推荐答案

您遇到的问题与您正在使用会话有关.当一个脚本有一个正在运行的会话时,它会锁定会话文件以防止可能破坏会话数据的并发写入.这意味着来自同一客户端的多个请求 - 使用相同的会话 ID - 不会同时执行,它们会排队并且一次只能执行一个.

The problem you are experiencing is related to the fact that you are using sessions. When a script has a running session, it locks the session file to prevent concurrent writes which may corrupt the session data. This means that multiple requests from the same client - using the same session ID - will not be executed concurrently, they will be queued and can only execute one at a time.

多个用户不会遇到此问题,因为他们将使用不同的会话 ID.这并不意味着您没有问题,因为您可能想在下载文件时访问该站点,或者设置一次下载多个文件.

Multiple users will not experience this issue, as they will use different session IDs. This does not mean that you don't have a problem, because you may conceivably want to access the site whilst a file is downloading, or set multiple files downloading at once.

解决方法其实很简单:调用session_write_close() 在开始输出文件之前.这将关闭会话文件,释放锁定并允许执行更多并发请求.

The solution is actually very simple: call session_write_close() before you start to output the file. This will close the session file, release the lock and allow further concurrent requests to execute.

这篇关于运行并发 PHP 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆