通过PHP处理多API请求

时间:2014-05-08 17:20:32

标签: php php-5.3

我有一个基本的PHP脚本,接受用户发送的文件。这段代码只是一个简单的API,用户通过POST请求发送文件。

我想知道如何处理超过3000名同时发送文件的用户?我需要使用线程吗?什么是最好的解决方案?

在用户网站上:(www.example.com)

 <form action="http://www.mywebsite.com/file.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="photo" size="25" />
<input type="submit" name="submit" value="Submit" />
  </form>

以下是我服务器上的代码(mywebsite.com)(file.php):

       //if they DID upload a file...
    if($_REQUEST['photo']['name'])
     {
//if no errors...
if(!$_REQUEST['photo']['error'])
{
    //now is the time to modify the future file name and validate the file
    $new_file_name = strtolower($_REQUEST['photo']['tmp_name']); //rename file
    if($_REQUEST['photo']['size'] > (1024000)) //can't be larger than 1 MB
    {
        $valid_file = false;
        $message = 'Oops!  Your file\'s size is to large.';
    }

    //if the file has passed the test
    if($valid_file)
    {
        //move it to where we want it to be
        move_uploaded_file($_REQUEST['photo']['tmp_name'], 'uploads/'.$new_file_name);
        $message = 'Congratulations!  Your file was accepted.';
    }
}
//if there is an error...
else
{
    //set that to be the returned message
    $message = 'Ooops!  Your upload triggered the following error:  '.$_REQUEST['photo']['error'];
}
    }

提前致谢

1 个答案:

答案 0 :(得分:0)

您不需要在PHP脚本中使用线程,因为这通常在网站上没有意义。根据Web服务器,它将确保负载在系统资源之间保持平衡。

每次有人访问API时,都会生成一个新的php进程,因此几个用户可以同时使用它,因为Web服务器将处理线程。

正如Ronni的评论中提到的,您可能还需要花一些时间来保护API免受攻击,这将有效地允许用户覆盖您的某个文件。解决此问题的一个好方法是简单地为文件提供一个随机名称而不是原始名称。


有多种技术可以优化您的服务。你应该注意的一些事情是实际的网络服务器(nginx,apache,lighttpd,IIS等)以及它们处理PHP文件的方式(例如mod_php,php_fcgi,php-fpm)。

由于您将处理文件传输,因此可能需要大量网络流量和I / O,您可能需要查看千兆位连接上的服务器以及极端情况下的固态驱动器或大型RAID配置。获取VPS或使用云实例通常是一个好主意,因为服务很容易扩展,在VPS上获取新硬件只需要重新启动,而专用服务器可能会在硬件交换或您交换时停机15-30分钟甚至可能不得不把一切都搬到另一台机器上。

在更极端的情况下,您可以考虑购买IP负载平衡器以平衡群集周围的负载,但这可能与同时传输的数量无关。

如果您对服务器软件或硬件有任何具体问题,可以在https://serverfault.com/上创建一个新问题,即服务器管理的Stack Overflow等效项。

关于压力测试,请查看this wikipedia page上的一些工具。