When using PHP as a simple crawler, we often encounter the need to download remote images, so the following is simple to achieve the requirements
1: Using Curl
For example, we have the following two pictures:
$images = [ ' Https://img.alicdn.com/tps/TB1jjaYOFXXXXa2aXXXXXXXXXXX-276-402.jpg_ 150x10000q90.jpg ', ' HTTPS://IMG.ALICDN.COM/TFS/TB15QQ5CGMPMEJJY1XBXXCWXVXA-520-280.JPG_Q90_.WEBP '];
In the first step, we can directly use the simplest code implementations:
functionDownload$url,$path= ' images/'){ $ch=Curl_init (); curl_setopt ($ch, Curlopt_ssl_verifypeer,false);//Trust any certificatecurl_setopt ($ch, Curlopt_url,$url); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_connecttimeout, 30); $file= Curl_exec ($ch); Curl_close ($ch); $filename=PathInfo($url,pathinfo_basename); $resource=fopen($path.$filename, ' a '); fwrite($resource,$file); fclose($resource);}
So when downloading remote pictures, you can:
foreach $images as $url ) { download ($url);}
1: Encapsulation into a class
After the idea is clear, we can encapsulate this basic function in a class:
classSpider { Public functionDownloadimage ($url,$path= ' images/') { $ch=Curl_init (); curl_setopt ($ch, Curlopt_ssl_verifypeer,false);//Trust any certificatecurl_setopt ($ch, Curlopt_url,$url); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_connecttimeout, 30); $file= Curl_exec ($ch); Curl_close ($ch); $filename=PathInfo($url,pathinfo_basename); $resource=fopen($path.$filename, ' a '); fwrite($resource,$file); fclose($resource); }}
Alternatively, we can optimize this slightly:
classSpider { Public functionDownloadimage ($url,$path= ' images/') { $ch=Curl_init (); curl_setopt ($ch, Curlopt_ssl_verifypeer,false);//Trust any certificatecurl_setopt ($ch, Curlopt_url,$url); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_connecttimeout, 30); $file= Curl_exec ($ch); Curl_close ($ch); $this->saveasimage ($url,$file,$path); } Private functionSaveasimage ($url,$file,$path) { $filename=PathInfo($url,pathinfo_basename); $resource=fopen($path.$filename, ' a '); fwrite($resource,$file); fclose($resource); }}
After encapsulation into a class, we can call the code to download the image:
$spider New Spider (); foreach $images as $url ) { $spider->downloadimage ($url);}
In this way, the generally accessible remote picture download is ok ....
PHP Download remote image to local