相关疑难解决方法(0)

使用PHP提供文件的最快方法

我正在尝试组合一个接收文件路径的函数,识别它是什么,设置适当的头,并像Apache一样提供服务.

我这样做的原因是因为我需要在提供文件之前使用PHP来处理有关请求的一些信息.

速度至关重要

virtual()不是一个选项

必须在共享托管环境中工作,用户无法控制Web服务器(Apache/nginx等)

这是我到目前为止所得到的:

File::output($path);

<?php
class File {
static function output($path) {
    // Check if the file exists
    if(!File::exists($path)) {
        header('HTTP/1.0 404 Not Found');
        exit();
    }

    // Set the content-type header
    header('Content-Type: '.File::mimeType($path));

    // Handle caching
    $fileModificationTime = gmdate('D, d M Y H:i:s', File::modificationTime($path)).' GMT';
    $headers = getallheaders();
    if(isset($headers['If-Modified-Since']) && $headers['If-Modified-Since'] == $fileModificationTime) {
        header('HTTP/1.1 304 Not Modified');
        exit();
    }
    header('Last-Modified: '.$fileModificationTime);

    // Read the file
    readfile($path);

    exit();
}

static function mimeType($path) {
    preg_match("|\.([a-z0-9]{2,4})$|i", $path, $fileSuffix);

    switch(strtolower($fileSuffix[1])) …
Run Code Online (Sandbox Code Playgroud)

php performance file-io x-sendfile

93
推荐指数
4
解决办法
5万
查看次数

标签 统计

file-io ×1

performance ×1

php ×1

x-sendfile ×1