smith
smith

Reputation: 5461

file corrupt when click download link

I try to use php to force the image jpg file download, I have implemented eth following code:

html

<a href = "filedownload.php?src=uploads/myimage.jpg&download=true>download this file</a>

download.php

 <?php
ob_start();
 include_once 'functions.php';

if (isset($_GET['download']) && $_GET['download'] == 'true')
  {    

  $src = sanitizeString($_GET['src']);
  header('Content-Description: File Transfer');   
  header('Content-Type: image/jpeg');  
  header('Content-Disposition: attachment; filename='.basename($src));  
  header('Content-Transfer-Encoding: binary');  
  header('Expires: 0');   
  header('Cache-Control: public');  
  header('Pragma: public');

  } 

 ?>

Suppose the full path of the image is "www.example.com/smith/topic/uploads/myimage.jpg", I have recieved the right image name and the download window is appeared as well, but the image is corrupt and with 1KB size, any one could tell me why, thanks a lot.

Upvotes: 2

Views: 2543

Answers (3)

Faraona
Faraona

Reputation: 1700

Here you are example how to use readfile function

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

Upvotes: 6

Faraona
Faraona

Reputation: 1700

Try to use:

header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );

Upvotes: 1

nos
nos

Reputation: 229108

You need some code that actually sends over the file. See e.g. readfile or fpassthru

Upvotes: 1

Related Questions