Serving file hosted on another server as download

后端 未结 2 520
一整个雨季
一整个雨季 2020-12-20 09:03

I have a simple, yet critical question (critical for my application)

I will have a file url as:

http://a.com/b.jpg
http://a.com/b.zip
http://a.com/b.         


        
相关标签:
2条回答
  • 2020-12-20 09:53
    1. store file outside web root
    2. filesize(filename) will get the file size
    3. as your forcing download you don't need to know the mime type
    0 讨论(0)
  • 2020-12-20 09:56

    I suppose you can use cURL to fire off a HEAD request for the target URL. This will let the web server hosting the target the mimetype and content length of the file.

    $url = 'http://www.example.com/path/somefile.ext';
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLOPT_NOBODY, true); // make it a HEAD request
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    $head = curl_exec($ch);
    
    $mimeType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    $path = parse_url($url, PHP_URL_PATH);
    $filename = substr($path, strrpos($path, '/') + 1);
    
    curl_close($ch); 
    

    Then, you can write back these headers to the HTTP request made on your script:

    header('Content-Type: '.$mimeType);
    header('Content-Disposition: attachment; filename="'.$filename. '";' );
    header('Content-Length: '.$size);
    

    And then you follow this up with the file contents.

    readfile($url);
    
    0 讨论(0)
提交回复
热议问题