0

I found a simple script on internet on how to upload files in php.

  <?php
require 'config.php';

if (isset ( $_SERVER ['REQUEST_METHOD'] ) == 'POST') {
 // when submit button is clicked
 if (isset ( $_POST ['submit'] )) {
  // get user's data
  $name = $_POST ['name'];
  $email = $_POST ['email'];
  $images = "";

  // check if user has added images
  if(strlen(($_FILES ['upload'] ['tmp_name'] [0])) != 0){
   $upload_dir = "images/";

   // move all uploaded images in directory
   for ($i = 0; $i < count($_FILES['upload']['name']); $i++) {
    $ext = substr(strrchr($_FILES['upload']['name'][$i], "."), 1);

    // generate a random new file name to avoid name conflict
    $fPath = md5(rand() * time()) . ".$ext";
    $images .= $fPath.";";

    $result = move_uploaded_file($_FILES['upload']['tmp_name'][$i], $upload_dir . $fPath);
   } 
  }else {
   // if user doesn't have any images, add default value
   $images .= "no images";
  }

  // write the user's data in database
  // prepare the query
  $query = "INSERT INTO users(name, email,images) VALUES
  ('$name', '$email','$images')";

  // TODO check if the user's informations are successfully added
  // in the database
  $result = mysql_query ( $query ); 
 }
}
?>

This script does a really good job overall but the only problem is that when I upload image files or pdf they open up in a new tab, they do not download. How do I make the uploaded image files automatically download when the download link is clicked on? Thanks in advance.

  • 1
    You can add a `Content-Disposition` header to the download which indicates that the response is a file to be saved. It's really up to the browser what to do with the response. Note that none of the code shown here is relevant. Uploading and downloading are two entirely separate operations. – David Aug 07 '16 at 12:41

1 Answers1

0

Add the download link as follows

<a href="link/to/your/download/image" download>Download link</a>

Add the following code in apache config

<Location "/images">
<Files *.*>
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</Files>
</Location>
coder
  • 906
  • 1
  • 12
  • 19