Method 1: Using the function file_get_contents() : function file_get_contents() is used to read a file into a string. This feature uses memory mapping methods supported by the server and thus improves performance by making it the preferred way to read file contents.
Syntax:file_get_contents ($path, $include_path, $context, $start, $max_length)
Program 1:
// Initialize the file URL into a variable
$url
=
’ https://contribute.engineerforengineer.org/wp-content/uploads /gfg-40.png ’
;
// Use the basename() function to return the base filename
$file_name
=
basename
(
$url
);
// Use the file_get_contents() function to get the file
// from the url and use the file_put_contents() function for
// save the file using the base name
if
(
file_put_contents
(
$file_name
,
file_get_contents
(
$url
))) {
echo
"File downloaded successfully"
;
}
else
{
echo
" File downloading failed. "
;
}
?>
Output: Before starting the program:
After starting the program:
Method 2: Using PHP Curl:cURL stands for "Client for URL", initially with an uppercase URL to make it obvious that it is dealing with URL. This is pronounced “see. URL ". There are two products libcurl and curl in the cURL project.Steps to download the file: - Initialize file url for variable
- Create cURL session
- Declare a variable and store the name of the directory where the uploaded file will be saved.
- Use the basename() function to return the base name of the file if specified path to the file.
- Save the file to the specified location.
- Open the location of the saved file in line write mode
- Set the option to transfer cURL
- Execute cURL session and close cURL session and free up all resources
- Close file
Example :
/ / Initialize the file URL into a variable
$ url
=
’ https://contribute.engineerforengineer.org/wp-content/uploads/gfg-40.png ’
;
// Initialize the cURL session
$ch
= curl_init (
$url
);
// Initialize the directory name, where
// file will be saved
$dir
=
’. /’
;
// Use the basename() function to return
// base file name
$file_name
=
basename
(
$url
);
// Save file to folder
$save_file_loc
=
$dir
.
$file_name
;
// Open file
$fp
=
fopen
(
$save_file_loc
,
’wb’
);
// It sets the option to pass cURL
curl_setopt (
$ch
, CURLOPT_FILE,
$fp
);
curl_setopt (
$ch
, CURLOPT_HEADER, 0);
// Execute cURL session
curl_exec (
$ch
);
// Closes the cURL session and releases all resources
curl_close (
$ch
);
// Close file
fclose (
$fp
);
?>
Output: Before starting the program:
After starting the program: