Typically, you don't need to use a server-side language like PHP to download images, zip files, pdf documents, exe files, and more. If the file is in a publicly accessible folder, you can simply create a link to it. When a user clicks the link, the browser will automatically download the file.
<a href="downloads/test.zip">Download Zip file</a>
<a href="downloads/masters.pdf">Download PDF file</a>
<a href="downloads/sample.jpg">Download Image file</a>
<a href="downloads/setup.exe">Download EXE file</a>
When you click a link to a PDF or image file, it won't download directly to your hard drive. Instead, it will open in your browser, and you can save it from there. However, zip and exe files are automatically downloaded to your hard drive by default.
With PHP's readfile()
function, you can make images or other files download directly to the user's hard drive. In this example, we'll create a simple image gallery that lets users download images with a single click.
Create a file named "image-gallery.php" and add the following code inside it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Image Gallery</title>
<style type="text/css">
.img-box{
display: inline-block;
text-align: center;
margin: 0 15px;
}
</style>
</head>
<body>
<?php
// Array containing sample image file names
$images = array("kites.jpg", "balloons.jpg");
// Loop through array to create image gallery
foreach($images as $image){
echo '<div class="img-box">';
echo '<img src="images/' . $image . '" width="200" alt="' . pathinfo($image, PATHINFO_FILENAME) .'">';
echo '<p><a href="download.php?file=' . urlencode($image) . '">Download</a></p>';
echo '</div>';
}
?>
</body>
</html>
If you look closely at the example code above, you'll notice that the download link points to a "download.php" file, and the URL includes the image file name as a query string. We've also used PHP's urlencode()
function to encode the image file names, ensuring they can be safely passed as URL parameters since file names might contain characters that are unsafe for URLs.
Below is the full code for the "download.php" file, which forces the image to download.
<?php
if(isset($_REQUEST["file"])){
// Get parameters
$file = urldecode($_REQUEST["file"]); // Decode URL-encoded string
/* Test whether the file name contains illegal characters
such as "../" using the regular expression */
if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $file)){
$filepath = "images/" . $file;
// Process download
if(file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
die();
} else {
http_response_code(404);
die();
}
} else {
die("Invalid file name!");
}
}
?>
Similarly, you can force the download of other file formats like Word docs, PDF files, etc.
The regular expression in the above example (line no-8) will not allow file names that start or end with a dot character (.
). For instance, it permits file names such as kites.jpg
or Kites.jpg
, myscript.min.js
but does not allow kites.jpg.
or .kites.jpg
.
Please check out the tutorial on regular expressions to learn more about regular expressions.