Downloading remote images with PHP is a common need — how do you do it? The principle: request the URL with curl and write the returned file stream to a target path.
<?php
/*
When building a simple crawler in PHP, you often need to download remote
images, so let's implement that requirement here.
*/
// For example, we have these 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'
];
class Spider
{
// download an image: takes a URL
public function downloadImage($url, $path = 'images/')
{
$ch = curl_init();
// request by URL
curl_setopt($ch, CURLOPT_URL, $url);
// return as a file stream instead of outputting directly to the browser
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// connection timeout for the request
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
// get the file path info
$this->saveAsImage($url, $file, $path);
}
// save the image
private function saveAsImage($url, $file, $path)
{
// get the file's basic info
$filename = pathinfo($url, PATHINFO_BASENAME);
// open the file and write it into the path
$resource = fopen($path . $filename, 'a');
fwrite($resource, $file);
fclose($resource);
}
}
// With the class wrapped up, we can call it like this to download images.
// That's enough for basic remote image downloading.
$spider = new Spider();
foreach ($images as $url) {
$spider->downloadImage($url);
}
Quantum Responses (0)