- /**
- * Download remote images to local
- *
- * @param string $url remote file address
- * @param string $filename 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 (the rest of the path is automatically generated based on the time system)
- * @param int $type The way to obtain the file remotely
- * @return json Returns the file name , file saving path
- * @author blog.snsgou.com
- */
- 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 the 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 = 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 . '/' . date('Y', time()) . '/' . date('m', time()) . '/' . date('d', time());
- $dirName = $dirName . '/' . date('Ym', time());
- if (!file_exists($dirName))
- {
- mkdir($dirName, 0777, true);
- }
-
- // Save the file
- $res = fopen($dirName . '/' . $fileName, 'a');
- fwrite($res, $file);
- fclose($res);
-
- return array (
- 'fileName' => $fileName,
- 'saveDir' => $dirName
- );
- }
Copy code
|