PHP download file script
Download those particular files on which the user has clicked. (It means download the files dynamically not a static file)
PHP download file features:
- The file name, which is passed via the query string, is sanitized by using the PHP function preg_replace() and filter_var()
- To make the script safer, use the PHP function pathinfo() to parse the file path, if this happens successfully, the script will continue the further file handling process.
- The file download script is also useful for bigger files
There are many approaches to download a file from a URL these are:-
Method 1: Using file_get_contents() function:
This function is used to read a file into a string.
This function uses memory mapping techniques that are supported by the server and thus enhances the performances making it a preferred way of reading the contents of a file.
Syntax:
file_get_contents($path, $include_path, $context, $start, $max_length)
Program 1:
<?php // Initialize a file URL to the variable $url = ' https://contribute.geeksforgeeks.org/wp-content/uploads/gfg-40.png'; // Use basename() function to return the base name of file $file_name = basename($url); // Use file_get_contents() function to get the file // from url and use file_put_contents() function to // save the file by using base name if(file_put_contents( $file_name,file_get_contents($url))) { echo "File downloaded successfully"; } else { echo "File downloading failed."; } ?> |
Output:
Before running the program:
The cURL stands for ‘Client for URLs’, originally with URL spelled in uppercase to make it obvious that it deals with URLs.
It is pronounced as ‘see URL’. The cURL project has two products libcurl and curl.
Steps to download the file:
- Initialize a file URL to the variable
- Create cURL session
- Declare a variable and store the directory name where the downloaded file will save.
- Use the basename() function to return the file basename if the file path is provided as a parameter.
- Save the file to the given location.
- Open the saved file location in write string mode
- Set the option for cURL transfer
- Perform cURL session and close cURL session and free all resources
- Close the file
Example:
<?php // Initialize a file URL to the variable $url = ' https://contribute.geeksforgeeks.org/wp-content/uploads/gfg-40.png'; // Initialize the cURL session $ch = curl_init($url); // Inintialize directory name where // file will be save $dir = './'; // Use basename() function to return // the base name of file $file_name = basename($url); // Save file into file location $save_file_loc = $dir . $file_name; // Open file $fp = fopen($save_file_loc, 'wb'); // It set an option for a cURL transfer curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); // Perform a cURL session curl_exec($ch); // Closes a cURL session and frees all resources curl_close($ch); // Close file fclose($fp); ?> |
Output:
Before running the program:
After running the program:
Syntax
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
- $filename: represents the file name
- $use_include_path: It is the optional parameter. It is by default false. You can set it to true to search the file in the included_path.
- $context: represents the context stream resource.
- int: It returns the number of bytes read from the file.
Download Text File in PHP
download1.php
<?php
$file_url = 'http://www.your_remote_server.com/f.txt';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: utf-8");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>
Method: 4 Download a File Through Anchor Link
HTML Code:
<a href="download.php?file=codexworld.png">Dowload File</a>
PHP Code (download.php):
<?php
if(!empty($_GET['file'])){
$fileName = basename($_GET['file']);
$filePath = 'files/'.$fileName;
if(!empty($fileName) && file_exists($filePath)){
// Define headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file
readfile($filePath);
exit;
}else{
echo 'The file does not exist.';
}
}
?>
PHP download files from a MySQL database
The PHP download code doesn’t hide the file name and in some situations, it might be better to use a unique string or ID as a key for the file download.
For example, use a string to receive the name of a file that is stored inside a secure MySQL database.
As file download.php:
<?php | |
ignore_user_abort(true); | |
set_time_limit(0); | |
$path = "/absolute_path_to_your_files/"; | |
$secret = 'your-secret-string'; | |
if (isset($_GET['fid']) && preg_match('/^([a-f0-9]{32})$/', $_GET['fid'])) { | |
$db = new mysqli('localhost', 'username', 'password', 'databasename'); | |
$result = $db->query(sprintf("SELECT filename FROM mytable WHERE MD5(CONCAT(ID, '%s')) = '%s'", $secret, $db->real_escape_string($_GET['fid']))); | |
if ($result_>num_rows == 1) { | |
$obj = $result->fetch_object(); | |
$fullPath = $path.$obj->filename; | |
if ($fd = fopen ($fullPath, "r")) { | |
// | |
// the other PHP download code | |
// | |
} | |
fclose ($fd); | |
exit; | |
} else { | |
die('no match'); | |
} | |
} else { | |
die('missing file ID'); | |
} |
Example:-
<?php
// Initialize a file URL to the variable
$url = 'https://contribute.geeksforgeeks.org/wp-content/uploads/gfg-40.png';
// Use basename() function to return the base name of file
$file_name = basename($url);
// Use file_get_contents() function to get the file
// from url and use file_put_contents() function to
// save the file by using base name
if(file_put_contents( $file_name,file_get_contents($url))) {
echo "File downloaded successfully";
}
else {
echo "File downloading failed.";
}
?>
Output:-
PHP File Downloading
<?php
$f="resume.doc";
$file = ("myfolder/$f");
$filetype=filetype($file);
$filename=basename($file);
header ("Content-Type: ".$filetype);
header ("Content-Length: ".filesize($file));
header ("Content-Disposition: attachment; filename=".$filename);
readfile($file);
?>
Example:- Forcing a download using readfile()
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
The above example will output something similar to:
================================================
0 Comments