Home >Backend Development >PHP Tutorial >Sharing of custom functions for downloading remote images implemented in PHP, _PHP tutorial

Sharing of custom functions for downloading remote images implemented in PHP, _PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:08:52963browse

Sharing custom functions for downloading remote images implemented in PHP,

Copy code The code is as follows:

/**
* PHP download remote images to local
*
* @param $url string remote file address
* @param $filename string The saved file name (if empty, it is a randomly generated file name, otherwise it is the original file name)
* @param $fileType array allowed file types
* @param $dirName string The path where the file is saved (the rest of the path is automatically generated based on the time system)
* @param $type int How to obtain files remotely
* @return json returns the file name and file saving path
* @author blog.snsgou.com
​*/
function getImage($url, $fileName = '', $dirName, $fileType = array('jpg', 'gif'), $type = 1)
{
if ($url == '')
{
return false;
}

// Get the original file name of the file
$defaultFileName = basename($url);

// Get file type
$suffix = substr(strrchr($url, '.'), 1);
if (!in_array($suffix, $fileType))
{
return false;
}

//Set the saved file name
$fileName = $fileName == '' ? time() . rand(0, 9) . '.' . $suffix : $defaultFileName;

// Get remote file resources
if ($type)
{
$ch = curl_init();
$timeout = 15; // Timeout
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file = curl_exec($ch);
curl_close($ch);
}
else
{
ob_start();
readfile($url);
$file = ob_get_contents();
ob_end_clean();
}

//Set file saving path
$dirName = $dirName . '/' . date('Y', time()) . '/' . date('m', time()) . '/' . date('d', time()) . '/';
if (!file_exists($dirName))
{
mkdir($dirName, 0777, true);
}

// Save file
$res = fopen($dirName . $fileName, 'a');
fwrite($res, $file);
fclose($res);

return "{'fileName':$fileName, 'saveDir':$dirName}";
}


// Example
// Return: {'fileName':13668030896.jpg, 'saveDir':/www/test/img/2013/04/24/}
echo getImage('http://img.wan.renren.com/images/2013/0430/1367294093164.jpg', '', 'd:/PHP/data', array('jpg', 'gif'), 1);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/949458.htmlTechArticlePHP implemented remote image download custom function sharing, copy the code as follows: php /** * PHP remote download Picture to local* * @param $url string remote file address* @param $filen...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn