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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3