// 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);