PHP File Download


PHP File Download:– When we click on a link pointing to text files,executable files(.exe extention file) etc ; these files has been saved in computer’s hard drive after clicking that href link but some file format like pdfs or .jpg files do not allow browser to download them. So in this scenerio we create a php script which allows a file to download.

In this tutorial I will show you how to create a link to a file which prompts the user for a download.

Note:–You should keep all files(jpg,png,pdf etc) for download inside htdocs.

Example // how to create a download link for .jpg type image

<!DOCTYPE html>
<head>
<style>
 .img-box{
        display: inline-block;
        text-align: center;
        margin: 0 15px;
    }
</style>
</head>
<body>
<?php
echo '<div class="img-box">';
echo '<img src="Tulips.jpg" width="200" height="100" alt="img error">';
echo "<p><a href=\"downloaddemoimg.php?file=Tulips.jpg\">Download image</p>";
?>
</body>
</html>

Example // Download Tulips.jpg

<?php
if(isset($_REQUEST["file"])){
	$file = urldecode($_REQUEST["file"]); // Decode URL-encoded string
       echo  $filepath = "./downloadimg/" . $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);
            exit;
        }
    //}
	else{
		echo "File does not exist.";
	}
}
?>

Advertisements

Add Comment

📖 Read More