Tutorial
php collects remote pictures and saves them locally
2024-03-23 23:27:30
Author:admin
/**
* Collect remote pictures
* @param string $url remote file address
* @param string $filename The saved file name (if empty, it is a randomly generated file name, otherwise it is the original file name)
* @param array $fileType allowed file types
* @param string $dirName The path where the file is saved
* @param int $type How to obtain files remotely
* @return json Returns the file name and file saving path
*/
function download_image($url, $fileName = '', $dirName, $fileType = array('jpg', 'gif', 'png'), $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 file name after saving
$fileName = $fileName == '' ? time() . rand(0, 9) . '.' . $suffix : $defaultFileName;
// Get remote file resources
if($type)
{
$ch = curl_init();
$timeout = 30;
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;
if (!file_exists($dirName))
{
mkdir($dirName, 0777, true);
}
// save file
$res = fopen($dirName . '/' . $fileName, 'a');
fwrite($res, $file);
fclose($res);
return array(
'fileName' => $fileName,
'saveDir' => $dirName
);
}