Are there any best practices to follow when dealing with Range requests in PHP?
When dealing with Range requests in PHP, it is important to properly handle the Range header sent by the client to serve partial content efficiently. One best practice is to check if the Range header is present in the request and then parse and process it accordingly to serve the requested range of data.
// Check if Range header is present in the request
if(isset($_SERVER['HTTP_RANGE'])) {
$range = $_SERVER['HTTP_RANGE'];
// Parse the Range header to get the start and end byte positions
$range = str_replace('bytes=', '', $range);
$range = explode('-', $range);
$start = intval($range[0]);
$end = isset($range[1]) ? intval($range[1]) : filesize($filepath) - 1;
// Set the appropriate headers to serve the partial content
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $start . '-' . $end . '/' . filesize($filepath));
// Read and output the requested range of data
$fp = fopen($filepath, 'rb');
fseek($fp, $start);
while(!feof($fp) && ftell($fp) <= $end) {
echo fread($fp, 8192);
}
fclose($fp);
} else {
// Serve the full content if Range header is not present
readfile($filepath);
}
Related Questions
- Are there alternative methods, besides PHP, to play sounds for notifications in web applications?
- How can the use of explicit numerical indices be optimized when working with arrays in PHP?
- How important is it for PHP developers to understand the code they are working with, rather than just copying and pasting snippets?