How to make a file load in PHP

I have a list of images and I want to download link with each image so that the user can upload the image.

so can someone advise me How to specify a link to download any file in php?

EDIT

I want the download bar to appear when I click the download link. I do not want to navigate the image that will be displayed in the browser.

+6
html php download
source share
4 answers

If you want to force download, you can use something like the following:

<?php // Fetch the file info. $filePath = '/path/to/file/on/disk.jpg'; if(file_exists($filePath)) { $fileName = basename($filePath); $fileSize = filesize($filePath); // Output headers. header("Cache-Control: private"); header("Content-Type: application/stream"); header("Content-Length: ".$fileSize); header("Content-Disposition: attachment; filename=".$fileName); // Output file. readfile ($filePath); exit(); } else { die('The provided file path is not valid.'); } ?> 

If you just link to this script using a regular link, the file will be downloaded.

By the way, the code snippet above should be executed at the beginning of the page (before any headers or HTML output appear). Also take care if you decide to create a function based on this for downloading arbitrary files - you need to make sure that you prevent directory traversal ( realpath , this is convenient, only allows downloading from a specific area, etc. if you accept input from $ _GET or $ _POST.

+29
source share

The solution is simpler than you think;) Simple use:

 header('Content-Disposition: attachment'); 

And it's all. For example, Facebook does the same.

+1
source share

In the HTML5 download attribute of the <a> tag, you can use:

 echo '<a href="path/to/file" download>Download</a>'; 

This attribute is used only if the href attribute is set.

There are no restrictions on acceptable values, and the browser will automatically detect the correct file extension and add it to the file (.img, .pdf, .txt, .html, etc.).

More details here .

+1
source share

You can do this in .htaccess and specify for different file extensions. Sometimes it is easier to do this than hard coding in an application.

 <FilesMatch "\.(?i:pdf)$"> ForceType application/octet-stream Header set Content-Disposition attachment </FilesMatch> 

By the way, you may need to clear your browser cache before it works properly.

0
source share

All Articles