PHP allows you to download remote images and save them to a local device,
When using PHP for simple crawling, we often encounter the need to download remote images, so the following is a simple implementation of this need.
1. Use curl
For example, we have the following two images:
$images = [ 'https://dn-laravist.qbox.me/2015-09-22_00-17-06j.png', 'https://dn-laravist.qbox.me/2015-09-23_00-58-03j.png'];
The first step is to use the simplest code:
function download($url, $path = 'images/'){ $ch = curl_init(); curl_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);}
You can download the remote image as follows:
foreach ( $images as $url ) { download($url);}
2. encapsulate a class
After clearing our mind, we can encapsulate this basic function into a class:
class Spider { public function downloadImage($url, $path = 'images/') { $ch = curl_init(); curl_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); }}
Here, we can also slightly optimize it as follows:
public function downloadImage($url, $path='images/') { $ch = curl_init(); curl_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 function saveAsImage($url, $file, $path) { $filename = pathinfo($url, PATHINFO_BASENAME); $resource = fopen($path . $filename, 'a'); fwrite($resource, $file); fclose($resource); }
After being encapsulated into a class, we can call the code to download the image as follows:
$spider = new Spider();foreach ( $images as $url ) { $spider->downloadImage($url);}
In this way, it is OK to deal with Basic remote image downloads.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.