फ़ाइल भेजने के लिए PHP का उपयोग करते समय फिर से शुरू करने योग्य डाउनलोड?


104

हम फ़ाइल डाउनलोडिंग के लिए PHP स्क्रिप्टिंग का उपयोग कर रहे हैं, क्योंकि हम डाउनलोड करने योग्य फ़ाइल के पूर्ण पथ को उजागर नहीं करना चाहते हैं:

header("Content-Type: $ctype");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=\"$fileName\"");
readfile($file);

दुर्भाग्य से हमने देखा कि इस स्क्रिप्ट के माध्यम से डाउनलोड किए गए अंत उपयोगकर्ता द्वारा फिर से शुरू नहीं किए जा सकते हैं।

क्या ऐसे PHP-आधारित समाधान के साथ पुन: प्रयोज्य डाउनलोड का समर्थन करने का कोई तरीका है?

जवाबों:


102

पहली चीज जो आपको करने की ज़रूरत है वह है कि Accept-Ranges: bytesसभी प्रतिक्रियाओं में हेडर भेजना , ग्राहक को यह बताना कि आप आंशिक सामग्री का समर्थन करते हैं। फिर, यदि Range: bytes=x-y हेडर के साथ अनुरोध प्राप्त होता है ( संख्याओं के साथ xऔर y) आप उस सीमा को पार्स करते हैं जो ग्राहक अनुरोध कर रहा है, तो फ़ाइल को हमेशा की तरह खोलें, xआगे बाइट्स की तलाश करें और अगला y- xबाइट भेजें । को भी प्रतिक्रिया सेट करें HTTP/1.0 206 Partial Content

कुछ भी परीक्षण किए बिना, यह कम या ज्यादा हो सकता है:

$filesize = filesize($file);

$offset = 0;
$length = $filesize;

if ( isset($_SERVER['HTTP_RANGE']) ) {
    // if the HTTP_RANGE header is set we're dealing with partial content

    $partialContent = true;

    // find the requested range
    // this might be too simplistic, apparently the client can request
    // multiple ranges, which can become pretty complex, so ignore it for now
    preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);

    $offset = intval($matches[1]);
    $length = intval($matches[2]) - $offset;
} else {
    $partialContent = false;
}

$file = fopen($file, 'r');

// seek to the requested offset, this is 0 if it's not a partial content request
fseek($file, $offset);

$data = fread($file, $length);

fclose($file);

if ( $partialContent ) {
    // output the right headers for partial content

    header('HTTP/1.1 206 Partial Content');

    header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize);
}

// output the regular HTTP headers
header('Content-Type: ' . $ctype);
header('Content-Length: ' . $filesize);
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Accept-Ranges: bytes');

// don't forget to send the data too
print($data);

मैं कुछ स्पष्ट याद कर सकता हूं, और मैंने त्रुटियों के कुछ संभावित स्रोतों को निश्चित रूप से अनदेखा किया है, लेकिन यह एक शुरुआत होनी चाहिए।

वहाँ एक है यहाँ आंशिक सामग्री का वर्णन, और मैं के लिए दस्तावेज़ पृष्ठ पर आंशिक सामग्री के बारे में कुछ जानकारी मिल गया fread


3
छोटा सा बग, आपकी नियमित अभिव्यक्ति होनी चाहिए: preg_match ('/ bytes = (\ d +) - (d d +)? /', $ _SERVER ['HTTP_RANGE'], $ माचिस)
deepwell 2

1
आप सही हैं और मैंने इसे बदल दिया है। हालाँकि, मैं वैसे भी बहुत सादगीपूर्ण हूँ, चश्मा के अनुसार आप "बाइट्स = एक्सवाई", "बाइट्स -एक्स", "बाइट्स = एक्स-", "बाइट्स = एक्सवाई, एब" आदि कर सकते हैं, इसलिए बग इतना ही है। पिछला संस्करण गायब अंत स्लैश था, प्रश्न चिह्न की कमी नहीं।
थियो

7
बहुत उपयोगी है, लेकिन मुझे इसे काम करने के लिए दो मामूली मोड़ बनाने पड़े: 1. यदि ग्राहक सीमा में समापन बिंदु नहीं भेजता (क्योंकि यह निहित है), $lengthतो नकारात्मक होगा। $length = (($matches[2]) ? intval($matches[2]) : $filesize) - $offset;ठीक करता है। 2. Content-Rangeपहले बाइट को बाइट मानता है 0, इसलिए अंतिम बाइट है $filesize - 1। इसलिए, यह होना चाहिए ($offset + $length - 1)
डेनिस

1
ऊपर बड़े डाउनलोड के लिए काम नहीं करता है, तो आपको "PHP घातक त्रुटि: XXXX बाइट्स की अनुमत मेमोरी आकार" (एक्सएक्सएक्स बाइट्स आवंटित करने की कोशिश की गई है) "। मेरे मामले में 100MB बहुत बड़ा था। आप मूल रूप से एक चर में सभी फ़ाइल को सहेजते हैं और इसे बाहर थूकते हैं।
सरह.फेरगूसन

1
आप बड़ी फ़ाइल समस्या को एक बार में सभी के बजाय विखंडू में पढ़कर हल कर सकते हैं।
डायनामिकेल

71

EDIT 2017/01 - मैंने PHP> = 7.0 https://github.com/DaveRandom/Resume में ऐसा करने के लिए एक पुस्तकालय लिखा

EDIT 2016/02 - एक मोनोलिथिक फ़ंक्शन के बजाय एक आदर्श उपयोग के मॉड्यूलर टूल के एक सेट को कोड पूरी तरह से फिर से लिखा गया। नीचे टिप्पणियों में उल्लिखित सुधारों को शामिल किया गया है।


एक परीक्षण, काम कर रहे समाधान (ऊपर दिए गए थियो के उत्तर के आधार पर) जो कुछ स्टैंडअलोन टूल के एक सेट में फिर से शुरू होने वाले डाउनलोड से संबंधित है। इस कोड के लिए PHP 5.4 या बाद के संस्करण की आवश्यकता होती है।

यह समाधान अभी भी केवल एक सीमा प्रति अनुरोध के साथ सामना कर सकता है, लेकिन किसी भी परिस्थिति में एक मानक ब्राउज़र के साथ जो मैं सोच सकता हूं, इससे समस्या नहीं होनी चाहिए।

<?php

/**
 * Get the value of a header in the current request context
 *
 * @param string $name Name of the header
 * @return string|null Returns null when the header was not sent or cannot be retrieved
 */
function get_request_header($name)
{
    $name = strtoupper($name);

    // IIS/Some Apache versions and configurations
    if (isset($_SERVER['HTTP_' . $name])) {
        return trim($_SERVER['HTTP_' . $name]);
    }

    // Various other SAPIs
    foreach (apache_request_headers() as $header_name => $value) {
        if (strtoupper($header_name) === $name) {
            return trim($value);
        }
    }

    return null;
}

class NonExistentFileException extends \RuntimeException {}
class UnreadableFileException extends \RuntimeException {}
class UnsatisfiableRangeException extends \RuntimeException {}
class InvalidRangeHeaderException extends \RuntimeException {}

class RangeHeader
{
    /**
     * The first byte in the file to send (0-indexed), a null value indicates the last
     * $end bytes
     *
     * @var int|null
     */
    private $firstByte;

    /**
     * The last byte in the file to send (0-indexed), a null value indicates $start to
     * EOF
     *
     * @var int|null
     */
    private $lastByte;

    /**
     * Create a new instance from a Range header string
     *
     * @param string $header
     * @return RangeHeader
     */
    public static function createFromHeaderString($header)
    {
        if ($header === null) {
            return null;
        }

        if (!preg_match('/^\s*(\S+)\s*(\d*)\s*-\s*(\d*)\s*(?:,|$)/', $header, $info)) {
            throw new InvalidRangeHeaderException('Invalid header format');
        } else if (strtolower($info[1]) !== 'bytes') {
            throw new InvalidRangeHeaderException('Unknown range unit: ' . $info[1]);
        }

        return new self(
            $info[2] === '' ? null : $info[2],
            $info[3] === '' ? null : $info[3]
        );
    }

    /**
     * @param int|null $firstByte
     * @param int|null $lastByte
     * @throws InvalidRangeHeaderException
     */
    public function __construct($firstByte, $lastByte)
    {
        $this->firstByte = $firstByte === null ? $firstByte : (int)$firstByte;
        $this->lastByte = $lastByte === null ? $lastByte : (int)$lastByte;

        if ($this->firstByte === null && $this->lastByte === null) {
            throw new InvalidRangeHeaderException(
                'Both start and end position specifiers empty'
            );
        } else if ($this->firstByte < 0 || $this->lastByte < 0) {
            throw new InvalidRangeHeaderException(
                'Position specifiers cannot be negative'
            );
        } else if ($this->lastByte !== null && $this->lastByte < $this->firstByte) {
            throw new InvalidRangeHeaderException(
                'Last byte cannot be less than first byte'
            );
        }
    }

    /**
     * Get the start position when this range is applied to a file of the specified size
     *
     * @param int $fileSize
     * @return int
     * @throws UnsatisfiableRangeException
     */
    public function getStartPosition($fileSize)
    {
        $size = (int)$fileSize;

        if ($this->firstByte === null) {
            return ($size - 1) - $this->lastByte;
        }

        if ($size <= $this->firstByte) {
            throw new UnsatisfiableRangeException(
                'Start position is after the end of the file'
            );
        }

        return $this->firstByte;
    }

    /**
     * Get the end position when this range is applied to a file of the specified size
     *
     * @param int $fileSize
     * @return int
     * @throws UnsatisfiableRangeException
     */
    public function getEndPosition($fileSize)
    {
        $size = (int)$fileSize;

        if ($this->lastByte === null) {
            return $size - 1;
        }

        if ($size <= $this->lastByte) {
            throw new UnsatisfiableRangeException(
                'End position is after the end of the file'
            );
        }

        return $this->lastByte;
    }

    /**
     * Get the length when this range is applied to a file of the specified size
     *
     * @param int $fileSize
     * @return int
     * @throws UnsatisfiableRangeException
     */
    public function getLength($fileSize)
    {
        $size = (int)$fileSize;

        return $this->getEndPosition($size) - $this->getStartPosition($size) + 1;
    }

    /**
     * Get a Content-Range header corresponding to this Range and the specified file
     * size
     *
     * @param int $fileSize
     * @return string
     */
    public function getContentRangeHeader($fileSize)
    {
        return 'bytes ' . $this->getStartPosition($fileSize) . '-'
             . $this->getEndPosition($fileSize) . '/' . $fileSize;
    }
}

class PartialFileServlet
{
    /**
     * The range header on which the data transmission will be based
     *
     * @var RangeHeader|null
     */
    private $range;

    /**
     * @param RangeHeader $range Range header on which the transmission will be based
     */
    public function __construct(RangeHeader $range = null)
    {
        $this->range = $range;
    }

    /**
     * Send part of the data in a seekable stream resource to the output buffer
     *
     * @param resource $fp Stream resource to read data from
     * @param int $start Position in the stream to start reading
     * @param int $length Number of bytes to read
     * @param int $chunkSize Maximum bytes to read from the file in a single operation
     */
    private function sendDataRange($fp, $start, $length, $chunkSize = 8192)
    {
        if ($start > 0) {
            fseek($fp, $start, SEEK_SET);
        }

        while ($length) {
            $read = ($length > $chunkSize) ? $chunkSize : $length;
            $length -= $read;
            echo fread($fp, $read);
        }
    }

    /**
     * Send the headers that are included regardless of whether a range was requested
     *
     * @param string $fileName
     * @param int $contentLength
     * @param string $contentType
     */
    private function sendDownloadHeaders($fileName, $contentLength, $contentType)
    {
        header('Content-Type: ' . $contentType);
        header('Content-Length: ' . $contentLength);
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Accept-Ranges: bytes');
    }

    /**
     * Send data from a file based on the current Range header
     *
     * @param string $path Local file system path to serve
     * @param string $contentType MIME type of the data stream
     */
    public function sendFile($path, $contentType = 'application/octet-stream')
    {
        // Make sure the file exists and is a file, otherwise we are wasting our time
        $localPath = realpath($path);
        if ($localPath === false || !is_file($localPath)) {
            throw new NonExistentFileException(
                $path . ' does not exist or is not a file'
            );
        }

        // Make sure we can open the file for reading
        if (!$fp = fopen($localPath, 'r')) {
            throw new UnreadableFileException(
                'Failed to open ' . $localPath . ' for reading'
            );
        }

        $fileSize = filesize($localPath);

        if ($this->range == null) {
            // No range requested, just send the whole file
            header('HTTP/1.1 200 OK');
            $this->sendDownloadHeaders(basename($localPath), $fileSize, $contentType);

            fpassthru($fp);
        } else {
            // Send the request range
            header('HTTP/1.1 206 Partial Content');
            header('Content-Range: ' . $this->range->getContentRangeHeader($fileSize));
            $this->sendDownloadHeaders(
                basename($localPath),
                $this->range->getLength($fileSize),
                $contentType
            );

            $this->sendDataRange(
                $fp,
                $this->range->getStartPosition($fileSize),
                $this->range->getLength($fileSize)
            );
        }

        fclose($fp);
    }
}

उदाहरण का उपयोग:

<?php

$path = '/local/path/to/file.ext';
$contentType = 'application/octet-stream';

// Avoid sending unexpected errors to the client - we should be serving a file,
// we don't want to corrupt the data we send
ini_set('display_errors', '0');

try {
    $rangeHeader = RangeHeader::createFromHeaderString(get_request_header('Range'));
    (new PartialFileServlet($rangeHeader))->sendFile($path, $contentType);
} catch (InvalidRangeHeaderException $e) {
    header("HTTP/1.1 400 Bad Request");
} catch (UnsatisfiableRangeException $e) {
    header("HTTP/1.1 416 Range Not Satisfiable");
} catch (NonExistentFileException $e) {
    header("HTTP/1.1 404 Not Found");
} catch (UnreadableFileException $e) {
    header("HTTP/1.1 500 Internal Server Error");
}

// It's usually a good idea to explicitly exit after sending a file to avoid sending any
// extra data on the end that might corrupt the file
exit;

यहाँ बहुत अच्छा कोड है। मुझे उस लाइन पर एक बग मिला जहां $ लंबाई निर्धारित है। होना चाहिए: $ लंबाई = $ अंत - $ शुरू + 1;
bobwienholt


3
क्या सामग्री-लंबाई को वास्तविक फ़ाइल आकार में सेट किया जाना चाहिए, या केवल आंशिक बाइट की संख्या भेजी जा रही है? यह पृष्ठ ऐसा दिखता है कि यह आंशिक बाइट्स होना चाहिए, लेकिन ऊपर दिए गए उदाहरण कोड में ऐसा नहीं है। w3.org/Protocols/rfc2616/rfc2616-sec14.html
willus

3
एक और छोटा टाइपो: $start = $end - intval($range[0]);होना चाहिएrange[1]
BurninLeo

1
@ sarah.ferguson कोड पूरी तरह से फिर से लिखा और अद्यतन किया गया है, ऊपर देखें।
डेवग्रैंड फेन

16

यह 100% सुपर चेक का काम करता है मैं इसका उपयोग कर रहा हूं और कोई समस्या नहीं है।

        /* Function: download with resume/speed/stream options */


         /* List of File Types */
        function fileTypes($extension){
            $fileTypes['swf'] = 'application/x-shockwave-flash';
            $fileTypes['pdf'] = 'application/pdf';
            $fileTypes['exe'] = 'application/octet-stream';
            $fileTypes['zip'] = 'application/zip';
            $fileTypes['doc'] = 'application/msword';
            $fileTypes['xls'] = 'application/vnd.ms-excel';
            $fileTypes['ppt'] = 'application/vnd.ms-powerpoint';
            $fileTypes['gif'] = 'image/gif';
            $fileTypes['png'] = 'image/png';
            $fileTypes['jpeg'] = 'image/jpg';
            $fileTypes['jpg'] = 'image/jpg';
            $fileTypes['rar'] = 'application/rar';

            $fileTypes['ra'] = 'audio/x-pn-realaudio';
            $fileTypes['ram'] = 'audio/x-pn-realaudio';
            $fileTypes['ogg'] = 'audio/x-pn-realaudio';

            $fileTypes['wav'] = 'video/x-msvideo';
            $fileTypes['wmv'] = 'video/x-msvideo';
            $fileTypes['avi'] = 'video/x-msvideo';
            $fileTypes['asf'] = 'video/x-msvideo';
            $fileTypes['divx'] = 'video/x-msvideo';

            $fileTypes['mp3'] = 'audio/mpeg';
            $fileTypes['mp4'] = 'audio/mpeg';
            $fileTypes['mpeg'] = 'video/mpeg';
            $fileTypes['mpg'] = 'video/mpeg';
            $fileTypes['mpe'] = 'video/mpeg';
            $fileTypes['mov'] = 'video/quicktime';
            $fileTypes['swf'] = 'video/quicktime';
            $fileTypes['3gp'] = 'video/quicktime';
            $fileTypes['m4a'] = 'video/quicktime';
            $fileTypes['aac'] = 'video/quicktime';
            $fileTypes['m3u'] = 'video/quicktime';
            return $fileTypes[$extention];
        };

        /*
          Parameters: downloadFile(File Location, File Name,
          max speed, is streaming
          If streaming - videos will show as videos, images as images
          instead of download prompt
         */

        function downloadFile($fileLocation, $fileName, $maxSpeed = 100, $doStream = false) {
            if (connection_status() != 0)
                return(false);
        //    in some old versions this can be pereferable to get extention
        //    $extension = strtolower(end(explode('.', $fileName)));
            $extension = pathinfo($fileName, PATHINFO_EXTENSION);

            $contentType = fileTypes($extension);
            header("Cache-Control: public");
            header("Content-Transfer-Encoding: binary\n");
            header('Content-Type: $contentType');

            $contentDisposition = 'attachment';

            if ($doStream == true) {
                /* extensions to stream */
                $array_listen = array('mp3', 'm3u', 'm4a', 'mid', 'ogg', 'ra', 'ram', 'wm',
                    'wav', 'wma', 'aac', '3gp', 'avi', 'mov', 'mp4', 'mpeg', 'mpg', 'swf', 'wmv', 'divx', 'asf');
                if (in_array($extension, $array_listen)) {
                    $contentDisposition = 'inline';
                }
            }

            if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
                $fileName = preg_replace('/\./', '%2e', $fileName, substr_count($fileName, '.') - 1);
                header("Content-Disposition: $contentDisposition;
                    filename=\"$fileName\"");
            } else {
                header("Content-Disposition: $contentDisposition;
                    filename=\"$fileName\"");
            }

            header("Accept-Ranges: bytes");
            $range = 0;
            $size = filesize($fileLocation);

            if (isset($_SERVER['HTTP_RANGE'])) {
                list($a, $range) = explode("=", $_SERVER['HTTP_RANGE']);
                str_replace($range, "-", $range);
                $size2 = $size - 1;
                $new_length = $size - $range;
                header("HTTP/1.1 206 Partial Content");
                header("Content-Length: $new_length");
                header("Content-Range: bytes $range$size2/$size");
            } else {
                $size2 = $size - 1;
                header("Content-Range: bytes 0-$size2/$size");
                header("Content-Length: " . $size);
            }

            if ($size == 0) {
                die('Zero byte file! Aborting download');
            }
            set_magic_quotes_runtime(0);
            $fp = fopen("$fileLocation", "rb");

            fseek($fp, $range);

            while (!feof($fp) and ( connection_status() == 0)) {
                set_time_limit(0);
                print(fread($fp, 1024 * $maxSpeed));
                flush();
                ob_flush();
                sleep(1);
            }
            fclose($fp);

            return((connection_status() == 0) and ! connection_aborted());
        }

        /* Implementation */
        // downloadFile('path_to_file/1.mp3', '1.mp3', 1024, false);

1
मैंने उतारा क्योंकि गति सीमा वास्तव में उपयोगी है, हालांकि एक फिर से शुरू की गई फ़ाइल (फ़ायरफ़ॉक्स) पर एमडी 5 की जांच ने एक बेमेल दिखाया। $ रेंज के लिए str_replace गलत है, एक और विस्फोट होना चाहिए, परिणाम बनाया संख्यात्मक और एक डैश सामग्री-श्रेणी हेडर में जोड़ा गया।
WhoIsRich

समर्थन दूरस्थ फ़ाइल डाउनलोड करने के लिए इसे कैसे अनुकूलित करें?
सियामक शाहपसंद

1
आपको 'सामग्री-प्रकार: $ सामग्री टाइप' को उद्धृत करने का मतलब है;
मैट

set_time_limit (0); मेरी राय में वास्तव में उचित नहीं है। 24 घंटे की एक अधिक उचित सीमा हो सकती है?
दुगुना

मेरे टाइपो की जाँच के लिए धन्यवाद :)!
user1524615

15

हाँ। समर्थन byteranges। RFC 2616 सेक्शन 14.35 देखें ।

इसका मूल रूप से मतलब है कि आपको Rangeहेडर पढ़ना चाहिए , और निर्दिष्ट ऑफसेट से फ़ाइल की सेवा शुरू करनी चाहिए ।

इसका मतलब है कि आप रीडफ़ाइल () का उपयोग नहीं कर सकते हैं, क्योंकि यह पूरी फ़ाइल परोसता है। इसके बजाय, सही स्थिति में fopen () पहले, फिर fseek () का उपयोग करें और फिर फ़ाइल की सेवा करने के लिए fpassthru () का उपयोग करें ।


4
fpassthru एक अच्छा विचार नहीं है यदि फ़ाइल कई मेगाबाइट है, तो आप मेमोरी से बाहर चला सकते हैं। चूडिय़ों में सिर्फ भय () और प्रिंट ()।
विलेम

3
fpassthru सैकड़ों मेगाबाइट के साथ यहां शानदार काम करता है। echo file_get_contents(...)काम नहीं किया (OOM)। इसलिए मुझे नहीं लगता कि यह कोई मुद्दा है। PHP 5.3।
जानूस ट्रॉल्सन

1
@JanusTroelsen नहीं, इसकी नहीं। यह सब आपके सर्वर के कॉन्फ़िगरेशन पर निर्भर करता है। यदि आपके पास एक मजबूत सर्वर है, जिसमें बहुत सारी मेमोरी PHP के लिए आवंटित है, तो शायद यह आपके लिए ठीक काम करता है। "कमजोर" कॉन्फ़िगरेशन (शाब्दिक: साझा होस्ट) का उपयोग करके fpassthruभी 50 एमबी फ़ाइलों पर विफल हो जाएगा। यदि आप कमजोर सर्वर कॉन्फ़िगरेशन पर बड़ी फ़ाइलों की सेवा कर रहे हैं, तो आपको निश्चित रूप से इसका उपयोग नहीं करना चाहिए। जैसा कि @immer सही ढंग से बताता है, fread+ printवह सब है, जो आपको इस मामले में चाहिए।
ट्रेडर

2
@trejder: readfile () : readfile () पर कोई भी मेमोरी की समस्या पेश नहीं करेगा, यहां तक ​​कि बड़ी फ़ाइलों को भेजने पर, अपने आप ही
जानूस ट्रॉल्सन

1
@trejder समस्या यह है कि आपने अपने आउटपुट बफरिंग को सही से कॉन्फ़िगर नहीं किया है। यह स्वचालित रूप से चकिंग करता है, यदि आप इसे बताते हैं: php.net/manual/en/… उदा। Output_buffering = 4096 (और यदि आपका फ्रेमवर्क इसकी अनुमति नहीं देता है, तो आप बेकार हैं)
ZJR

11

"अपने खुद के रोल" PHP कोड के बिना इसे हल करने का एक बहुत अच्छा तरीका mod_xsendfile अपाचे मॉड्यूल का उपयोग करना है। फिर PHP में, आप बस उपयुक्त हेडर सेट करते हैं। अपाचे अपना काम करने के लिए हो जाता है।

header("X-Sendfile: /path/to/file");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; file=\"filename\"");

2
यदि आप भेजने के बाद फ़ाइल को अनलिंक करना चाहते हैं तो क्या होगा?
जानूस ट्रॉल्सन

1
यदि आप भेजने के बाद फ़ाइल को अनलिंक करना चाहते हैं, तो संकेत करने के लिए एक विशेष ध्वज की आवश्यकता है, देखें XSendFilePath <absolute path> [AllowFileDelete]( tn123.org/mod_xsendfile/beta )।
जेन्स ए। कोच

9

आप एक नया PECL मॉड्यूल स्थापित करने के लिए तैयार हैं, तो सबसे आसान तरीका पीएचपी साथ Resumeable डाउनलोड का समर्थन करने के माध्यम से होता है http_send_file(), इस तरह

<?php
http_send_content_disposition("document.pdf", true);
http_send_content_type("application/pdf");
http_throttle(0.1, 2048);
http_send_file("../report.pdf");
?>

स्रोत: http://www.php.net/manual/en/function.http-send-file.php

हम इसका उपयोग डेटाबेस-संग्रहित सामग्री की सेवा के लिए करते हैं और यह एक आकर्षण की तरह काम करता है!


3
एक जादू की तरह काम करता है। हालाँकि इस बात का ख्याल रखें कि आपके पास आउटपुट बफरिंग (ob_start आदि) चालू न हों। विशेष रूप से बड़ी फाइलें भेजते समय, यह पूरी तरह से अनुरोधित सीमा को बफर कर देगा।
पीटर वैन जिन्केल

यह PHP में कब जोड़ा गया था? हमेशा से रहा है?
थोमथोम

1
वह Pecl है, PHP नहीं। मेरे पास यह कार्य नहीं है।
जियो

4

शीर्ष उत्तर में विभिन्न बग हैं।

  1. प्रमुख बग: यह रेंज हेडर को सही तरीके से हैंडल नहीं करता है। इसके बजाय का bytes a-bमतलब होना चाहिए , और संभाला नहीं है।[a, b][a, b)bytes a-
  2. मामूली बग: यह आउटपुट को संभालने के लिए बफर का उपयोग नहीं करता है। यह बहुत अधिक मेमोरी का उपभोग कर सकता है और बड़ी फ़ाइलों के लिए कम गति का कारण बन सकता है।

यहाँ मेरा संशोधित कोड है:

// TODO: configurations here
$fileName = "File Name";
$file = "File Path";
$bufferSize = 2097152;

$filesize = filesize($file);
$offset = 0;
$length = $filesize;
if (isset($_SERVER['HTTP_RANGE'])) {
    // if the HTTP_RANGE header is set we're dealing with partial content
    // find the requested range
    // this might be too simplistic, apparently the client can request
    // multiple ranges, which can become pretty complex, so ignore it for now
    preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
    $offset = intval($matches[1]);
    $end = $matches[2] || $matches[2] === '0' ? intval($matches[2]) : $filesize - 1;
    $length = $end + 1 - $offset;
    // output the right headers for partial content
    header('HTTP/1.1 206 Partial Content');
    header("Content-Range: bytes $offset-$end/$filesize");
}
// output the regular HTTP headers
header('Content-Type: ' . mime_content_type($file));
header("Content-Length: $filesize");
header("Content-Disposition: attachment; filename=\"$fileName\"");
header('Accept-Ranges: bytes');

$file = fopen($file, 'r');
// seek to the requested offset, this is 0 if it's not a partial content request
fseek($file, $offset);
// don't forget to send the data too
ini_set('memory_limit', '-1');
while ($length >= $bufferSize)
{
    print(fread($file, $bufferSize));
    $length -= $bufferSize;
}
if ($length) print(fread($file, $length));
fclose($file);

इसकी आवश्यकता क्यों है ini_set('memory_limit', '-1');?
मिक्को रेंटालीनें

1
@ मायको रेंटालैनेन मैं भूल गया। आप इसे हटाकर देख सकते हैं कि क्या होता है।
माईगॉड

1
दुर्भाग्य से आप $ मैचों के मामले में $ $ असाइनमेंट में एक त्रुटि फेंक देंगे [2] सेट नहीं है (उदाहरण के लिए "रेंज = 0-" अनुरोध के साथ)। मैंने इसके बजाय इसका इस्तेमाल किया:if(!isset($matches[2])) { $end=$fs-1; } else { $end = intval($matches[2]); }
Skynet

3

हां, आप उसके लिए रेंज हेडर का उपयोग कर सकते हैं। आपको पूर्ण डाउनलोड के लिए क्लाइंट को 3 और हेडर देने की आवश्यकता है:

header ("Accept-Ranges: bytes");
header ("Content-Length: " . $fileSize);
header ("Content-Range: bytes 0-" . $fileSize - 1 . "/" . $fileSize . ";");

एक बाधित डाउनलोड के लिए आपको रेंज अनुरोध हेडर की जांच करने की आवश्यकता है:

$headers = getAllHeaders ();
$range = substr ($headers['Range'], '6');

और इस स्थिति में 206 स्टेटस कोड वाली सामग्री परोसना न भूलें:

header ("HTTP/1.1 206 Partial content");
header ("Accept-Ranges: bytes");
header ("Content-Length: " . $remaining_length);
header ("Content-Range: bytes " . $start . "-" . $to . "/" . $fileSize . ";");

आपको अनुरोध हैडर से $ शुरुआत और $ चर प्राप्त होंगे, और फ़ाइल में सही स्थिति की तलाश के लिए fseek () का उपयोग करना होगा।


2
@ceejayoz: getallheaders () एक php फंक्शन है जो आपको मिलता है यदि आप Apache uk2.php.net/getallheaders
टॉम हैघ


2

छोटा संगीतकार सक्षम वर्ग जो pecl http_send_file के समान कार्य करता है। इसका मतलब है फिर से शुरू होने वाले डाउनलोड और थ्रॉटल के लिए समर्थन। https://github.com/diversen/http-send-file


1

HTTP में फिर से डाउनलोडिंग Rangeहेडर के माध्यम से किया जाता है । यदि अनुरोध में Rangeहेडर होता है , और यदि अन्य संकेतक (जैसे If-Match, If-Unmodified-Since) इंगित करते हैं कि डाउनलोड शुरू होने के बाद से सामग्री नहीं बदली गई है, तो आप 206 प्रतिसाद कोड देते हैं (200 के बजाय), बाइट्स की सीमा को इंगित करें जो आप लौट रहे हैं। में Content-Rangeशीर्ष लेख है, तो प्रतिक्रिया शरीर में है कि श्रृंखला प्रदान करते हैं।

मुझे नहीं पता कि PHP में यह कैसे करना है, हालांकि।


1

धन्यवाद थियो! आपका तरीका सीधे डिवोर्स स्ट्रीमिंग के काम नहीं आया क्योंकि मैंने पाया कि डिवएक्स प्लेयर बाइट्स = 9932800- जैसी रेंज भेज रहा था।

लेकिन इसने मुझे दिखाया कि यह कैसे करना है धन्यवाद: डी

if(isset($_SERVER['HTTP_RANGE']))
{
    file_put_contents('showrange.txt',$_SERVER['HTTP_RANGE']);

0

आप किसी भी ब्राउज़र में बाइट रेंज अनुरोध समर्थन के लिए नीचे दिए गए कोड का उपयोग कर सकते हैं

    <?php
$file = 'YouTube360p.mp4';
$fileLoc = $file;
$filesize = filesize($file);
$offset = 0;
$fileLength = $filesize;
$length = $filesize - 1;

if ( isset($_SERVER['HTTP_RANGE']) ) {
    // if the HTTP_RANGE header is set we're dealing with partial content

    $partialContent = true;
    preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);

    $offset = intval($matches[1]);
    $tempLength = intval($matches[2]) - 0;
    if($tempLength != 0)
    {
        $length = $tempLength;
    }
    $fileLength = ($length - $offset) + 1;
} else {
    $partialContent = false;
    $offset = $length;
}

$file = fopen($file, 'r');

// seek to the requested offset, this is 0 if it's not a partial content request
fseek($file, $offset);

$data = fread($file, $length);

fclose($file);

if ( $partialContent ) {
    // output the right headers for partial content
    header('HTTP/1.1 206 Partial Content');
}

// output the regular HTTP headers
header('Content-Type: ' . mime_content_type($fileLoc));
header('Content-Length: ' . $fileLength);
header('Content-Disposition: inline; filename="' . $file . '"');
header('Accept-Ranges: bytes');
header('Content-Range: bytes ' . $offset . '-' . $length . '/' . $filesize);

// don't forget to send the data too
print($data);
?>
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.