The following are three commonly used methods for downloading network images using PHP. Of course, these three methods are not omnipotent. Sometimes the download fails due to network problems or permission issues with online images (big sites generally have anti-leeching protection).
Let’s take a look, it is often used in actual work.
Advantages: Simple.
Disadvantages: Relatively low efficiency.
There are two main functions used in this method file_get_contents
and file_put_contents
This method is very simple. In layman's terms, it means to get the image content first, and then put it into in the file.
The code is as follows:
<?php $imgFile = 'http://***.***.***/Uploads/20200424/1587710975CZlGeB.jpg'; // 获取文件名 $imgName = trim(strrchr($imgFile, '/'), '/'); file_put_contents($imgName, file_get_contents($imgFile));
The most commonly used method by individuals.
Disadvantages: A little more complicated. To master the usage of curl
, you need to know the meaning of some curl options.
Advantages: high efficiency, easy to support https;
curl is very powerful and is a skill that PHPer must master, so it is recommended that everyone use this method. The idea of this method is to use the curl tool to obtain the information of the remote image, and then save the information to a local file. I didn't verify the results of curl_exec
here, just to be lazy.
Regarding the usage of curl, if you want to know more about it, you can search for curl on the PHP Chinese website.
$imgFile = 'https://***.***.***/uploads/20200121/bd873d80da430f8b74ef1ee751945595.png'; function down_img($imgUrl) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $imgUrl); // 请求地址 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 不直接输出信息 // 可以访问https请求 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 执行curl并获取数据 $results = curl_exec($ch); $imgName = trim(strrchr($imgUrl, '/'), '/'); $fp = fopen($imgName, 'w'); fwrite($fp, $results); // 执行完毕后,记得关闭资源 curl_close($ch); } down_img($imgFile);
This method is also very simple and uses PHP file management knowledge. First create two file handles, one for reading the binary information of the remote image, and the other for saving the image information.
<?php $imgFile = ' $imgName = trim(strrchr($imgFile, '/'), '/'); // 读取远程图片资源 $source = fopen($imgFile, 'rb'); // 创建本地文件资源句柄,用于保存图片信息 $down = fopen($imgName, 'wb'); while ($chunk = fread($source,1024)){ fwrite($down, $chunk, 1024); } fclose($source); fclose($down);
The first and second methods below are mainly used in personal work. One more thing, downloading pictures does not matter, but you should pay attention to how to use the downloaded pictures. If used incorrectly, infringement issues may arise.
The above is the detailed content of Summary of three commonly used methods for downloading network images in PHP. For more information, please follow other related articles on the PHP Chinese website!