Home >Backend Development >PHP Tutorial >How Can I Enable Resumable Downloads in My PHP File Transfer Script?
When transferring files using PHP scripts for security purposes, the absolute path of downloadable files often needs to be concealed. However, traditional PHP file transfer scripts may not support resumable downloads, causing inconvenience for end users who experience connection interruptions.
To enable resumable downloads, the following steps can be taken:
Below is a sample implementation of these principles in PHP:
$filesize = filesize($file); $offset = 0; $length = $filesize; if (isset($_SERVER['HTTP_RANGE'])) { preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches); $offset = intval($matches[1]); $length = intval($matches[2]) - $offset; } $file = fopen($file, 'r'); fseek($file, $offset); $data = fread($file, $length); fclose($file); if ($offset > 0) { header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize); } header('Content-Type: ' . $ctype); header('Content-Length: ' . $filesize); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header('Accept-Ranges: bytes'); print($data);
This script first checks if a partial content request was made. If so, it parses the range from the Range header, seeks to the appropriate offset in the file, and sends the requested byte range. The script also sets the Accept-Ranges header to bytes and sends the appropriate HTTP status code for partial content if necessary.
By implementing these measures, resumable downloads can be supported using PHP file transfer scripts, providing a robust solution for file transfers that can resume after interruptions.
The above is the detailed content of How Can I Enable Resumable Downloads in My PHP File Transfer Script?. For more information, please follow other related articles on the PHP Chinese website!