0

I was trying to write a script through which user can download the image directly.
Here is the code i end up with,

   <?php
        $fileContents   =   file_get_contents('http://xxx.com/images/imageName.jpg');
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.urlencode("http://xxx.com/images/imageName.jpg"));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($fileContents));
        ob_clean();
        flush();
        echo $fileContents;
        exit;
    ?>

But everytime i hit the url for the above script in the browser it returns a file with zero byte data.
would you like to help me to resolve this problem ?

Tarun
  • 3,162
  • 3
  • 29
  • 45
  • Do you want to force download remote server's file ? – Dhruv Patel Jan 18 '13 at 06:14
  • Then It may be possible that other server has .htaccess enabled that is not allowing the files to be accessed directly from other sources. – Dhruv Patel Jan 18 '13 at 06:17
  • @DhruvPatel but if i directly hit the remote server url(where the image is store) in the browser ,the image gets downloaded easily – Tarun Jan 18 '13 at 06:20
  • Try changing your content type to `"image/jpg"` as it's a jpg file. Aslo check this may helps you -> http://stackoverflow.com/questions/4706073/php-force-download-causing-0-byte-files – Rikesh Jan 18 '13 at 06:21
  • 1
    That's because `filesize($fileContents)` returns 0. – Ja͢ck Jan 18 '13 at 06:24
  • @mark you were absolutely right,thanks – Tarun Jan 18 '13 at 07:12

2 Answers2

0

Try the code below

<?php 
    $file_name = 'file.png';
    $file_url = 'http://www.myremoteserver.com/' . $file_name;
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"".$file_name."\""); 
    readfile($file_url);
?>

Read more , Read this tutorial too

Community
  • 1
  • 1
Techie
  • 44,706
  • 42
  • 157
  • 243
0

I notice that you use filesize on the contents of the file instead of at the filename itself;

Your code would work if it was:

<?php
    $filename = 'http://xxx.com/images/imageName.jpg';
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.urlencode($filename));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filename));
    ob_clean(); // not necessary
    flush();  // not necessary
    echo file_get_contents($filename); // or just use readfile($filename);
    exit;
?>
user1914292
  • 1,586
  • 13
  • 38