Fastest Way to Serve a File Using PHP
When you need to intercept a request, process data, and then deliver a static file without handing control over to the web server's default handler, performance becomes a critical metric. The naive approach often involves reading the entire file into memory or using functions that introduce unnecessary overhead. However, in a shared hosting environment where you lack root access to configure Apache or Nginx to serve files directly, there is a more efficient path within PHP itself.
The most performant method relies on readfile(). This function reads the file from disk and writes it directly to the output buffer without loading the entire contents into memory first. It effectively bypasses the overhead of creating a string representation of the file in RAM, which is crucial when dealing with large assets like images or video streams.
Your current implementation correctly identifies that virtual() is not an option for this specific use case and acknowledges the constraints of shared hosting. However, there are significant optimizations to apply to the header handling and MIME type detection logic you have presented.
Optimizing MIME Type Detection
A common pitfall in file-serving scripts is relying on a simple regex switch statement based solely on the file extension. While your current mimeType() function handles many cases, it relies on a hardcoded list of extensions. This approach breaks down quickly when encountering less common formats or when case sensitivity varies across operating systems (e.g., .JPG vs .jpg).
Furthermore, the fallback logic in your code attempts to use mime_content_type() but assigns its return value to $fileSuffix, which is already an array from the previous preg_match. This will result in a type error or unexpected behavior.
To ensure accuracy and speed, you should prioritize the built-in function over regex where possible. Modern PHP versions support checking the file extension directly using pathinfo(), but the most robust solution that mimics Apache's behavior is to use mime_content_type() as a primary check before falling back to extensions, or vice versa depending on your specific security requirements. If you must stick to extensions for speed and simplicity in shared hosting, ensure the switch statement covers all variations (e.g., .jpeg, .jpg) without relying on regex groups that might return empty strings if not checked properly.
Handling Caching Headers Correctly
Your implementation of conditional GET requests using If-Modified-Since is a good start for reducing bandwidth usage. However, there is a subtle bug in how you retrieve the modification time. You are using gmdate() to generate the header string, but this function requires a timestamp as an argument. In your code, File::modificationTime($path) likely returns a Unix timestamp (integer).
The logic for comparing headers also needs scrutiny. The If-Modified-Since header sent by the browser is typically in GMT. When you generate $fileModificationTime, ensure it matches the timezone expected by the client or normalize both to UTC before comparison. A mismatch here forces the server to send the full file every time, negating the benefit of caching.
Additionally, always set Last-Modified before checking the If-Modified-Since condition to ensure the response headers are complete. Your current code does this correctly by setting the header after the check, which is fine, but note that Apache and Nginx often cache these headers automatically; your script must explicitly send them if you want to enforce strict caching behavior.
The readfile() Advantage
Once headers are set, readfile() is the gold standard for serving files in PHP. It returns the number of bytes sent or 0 on success. If you need to know exactly how many bytes were transmitted (for logging or debugging), you can capture the return value:
$bytesSent = readfile($path);
if ($bytesSent === false) {
http_response_code(500);
echo 'Error reading file';
}
This function is non-blocking in terms of memory usage and utilizes the underlying OS file I/O efficiently. It does not hold the file in a variable, making it the fastest option available within the PHP runtime.
Final Considerations for Shared Hosting
Since you are operating in a shared environment, you must ensure that readfile() is allowed to access the target path. Check file permissions on both the script and the target file. If the file is owned by www-data but readable only by the owner, the script will fail with a permission error even if the logic is correct.
For maximum speed in shared hosting where you cannot tune php.ini, minimize the number of function calls before readfile(). Your current structure checks existence and sets headers first, which is the correct order of operations. Do not attempt to read the file content twice or use fopen/stream_copy_to_stream unless you specifically need to modify the stream on-the-fly, as these add unnecessary latency compared to readfile().
By refining your MIME detection and ensuring your cache headers are strictly aligned with UTC timezones, you can achieve near-native performance levels for static file delivery using pure PHP. For developers looking to offload this logic entirely, platforms like https://laravelcompany.com offer robust frameworks that handle these low-level concerns automatically, allowing you to focus on application logic rather than file I/O optimization.