- 5 years ago
- Zaid Bin Khalid
- 94,683 Views
-
24
In this post, I will try to explain to you how you can download any file by its URL with the help of PHP. You can do it in many ways but in this tutorial, I will explain to you a few tricks.
First Method
We will use file_get_contents() a built-in function of PHP. This function is similar to file() the only difference is file_get_contents() returns the file in a string. This function uses memory mapping techniques and it is a preferred way to read file content.
file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] ) : string
The function returns the read data or FALSE on failure.
<?php
$url = 'https://neilpatel.com/wp-content/uploads/2019/08/google.jpg';
$urlPdf = 'http://www.africau.edu/images/default/sample.pdf';
$file_name = basename($url);
//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!";
}
?>
The above function will save the file on the same path where you run the script of PHP. If you want to download the file in your desired location then you need to set some headers. That is why I write a function given below that you can use to save file form URL into your local system.
<?php
function df($urlFile){
$file_name = basename($urlFile);
//save the file by using base name
$fn = file_put_contents($file_name,file_get_contents($urlFile));
header("Expires: 0");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Content-type: application/file");
header('Content-length: '.filesize($file_name));
header('Content-disposition: attachment; filename="'.basename($file_name).'"');
readfile($file_name);
}
?>
The usage of the above function is given below.
<?php
$url = 'https://neilpatel.com/wp-content/uploads/2019/08/google.jpg';
$urlPdf = 'http://www.africau.edu/images/default/sample.pdf';
df($urlPdf);
?>
Second Method.
In this method, I will show you how you can download a file with the helo of CURL another built-in function of PHP. If you use the below function you can save the file directly into your system by giving your desired location.
<?php
function dfCurl($url){
$ch = curl_init($url);
$dir = '../YourDirName/';
$fileName = basename($url);
$saveFilePath = $dir . $fileName;
$fp = fopen($saveFilePath, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
}
?>
The usage of the above function is given below.
$urlPdf = 'http://www.africau.edu/images/default/sample.pdf';
dfCurl($urlPdf);
You can use any above function to download the file into your system or into your server.
- 5 years ago
- Zaid Bin Khalid
- 94,683 Views
-
24