In the previous article "Example demonstrates how to call a PHP function when a button is clicked", I introduced to you how to call a PHP function when a button is clicked. Friends in need can learn about it~
The topic of this article is how to download files from URL through PHP?
There are actually many ways to download files from URLs, but this article will focus on two methods:
The first method:
Use file_get_contents () Function: The file_get_contents() function is used to read files into strings. This function uses server-supported memory mapping technology, which improves performance and makes it the preferred way to read file contents.
Syntax:
file_get_contents($path, $include_path, $context, $start, $max_length)
Create a test.php sample file with the following content:
Copy after login
The running results show:
文件下载成功
Now we can Check whether the "6125a391e4e76689.png" file was successfully saved in the same directory as the test.php file:
The file was successfully saved from the URL.
Second method:Use PHP Curl
Create a test.php sample file, the sample code is as follows:
Copy after login
Run the test.php file Then you can view the downloaded and saved file at the specified location.
This method implements the specific steps to download files:
Initialize the file URL as a variable
Create a cURL session
Declare a variable and store the name of the directory where the downloaded file will be saved.
If the file path is provided as a parameter, use the basename() function to return the file base name.
Save the file to the given location.
Open the saved file location by writing a string
Set cURL transfer options
Execute the cURL session and close the cURL session and release all resources
Close the file
Finally, I recommend the latest and most comprehensive "PHP Video tutorial》~Come and learn!
The above is the detailed content of Two ways to quickly download files from URL in PHP. For more information, please follow other related articles on the PHP Chinese website!