Basically, most of files such .ZIP, .EXE, .DOCX etc files are easy to download, its just matter of an hyperlink but what about PHP, HTML files?
How do you share your 'PHP file' to download in your website? If you just placed a link of PHP file it get executed. Same happens with PHP,HTML and other several file types. Some website owner choose Google Drive to store and download file but it gives bad impression to visitors.
So you must force to download instead of executing. How can you force file to download? Don't worry, today you are going to learn to download PHP file without executing.
How to Force File to Download with PHP?
Here is full code to force file to download,
<?php
$file_path = "download/file.php";
//Check File Exists or Not
if (file_exists($file_path)) {
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Content-Type: application/octet-stream');
header('Content-Length:'.filesize($file_path));
//Fix IE issue
header('Cache-Control:private');
header('Pragma: private');
//Read the file to download
readfile($file_path);
} else {
die('File Not Found');
}
?>
If you allow user to change $file_path value then your sensitive data may be downloaded by user. So use this code if user/visitors can not change $file_path else use code given below:
Store all file paths which you want to allow user to download in $allow_files extension. It will check if the given file is inside an array or not.
<?php
//Change File Path
$file_path = "download/file.php";
//Store all files allowed to download
$allow_files = array('download/file.php','download/pujan.php','download/anotherfile.php','download/new.php');
//Check File is allowed to download or not
if (in_array($file_path, $allow_files) && file_exists($file_path)) {
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Content-Type: application/octet-stream');
header('Content-Length:'.filesize($file_path));
//Fix IE issue
header('Cache-Control:private');
header('Pragma: private');
//Read the file to download
readfile($file_path);
} else {
die('Error: File Not Found');
}
?>
Hope you liked it,
Don't forgot to share this with your friends...