This article describes how to download remote image user-defined functions in PHP. This article provides the implementation code and the usage method, for more information, see the following code:
<? Php
/**
* PHP downloads remote images to a local device
*
* @ Param $ url string remote file address
* @ Param $ filename string name of the saved file (if it is null, it is a randomly generated file name; otherwise, it is the original file name)
* @ Param $ fileType the file type allowed by array
* @ Param $ dirName string file storage path (the rest of the path is automatically generated based on time)
* @ Param $ type int remote file retrieval method
* @ Return json returns the file name and file storage path.
* @ Author blog.snsgou.com
*/
Function getImage ($ url, $ fileName = '', $ dirName, $ fileType = array ('jpg ', 'GIF'), $ type = 1)
{
If ($ url = '')
{
Return false;
}
// Obtain the original file name
$ DefaultFileName = basename ($ url );
// Obtain the file type
$ Suffix = substr (strrchr ($ url, '.'), 1 );
If (! In_array ($ suffix, $ fileType ))
{
Return false;
}
// Set the saved file name
$ FileName = ''? Time (). rand (0, 9). '.'. $ suffix: $ defaultFileName;
// Obtain 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 the file storage path
$ DirName = $ dirName. '/'. date ('Y', time ()). '/'. date ('M', time ()). '/'. date ('D', time ()). '/';
If (! File_exists ($ dirName ))
{
Mkdir ($ dirName, 0777, true );
}
// Save the file
$ Res = fopen ($ dirName. $ fileName, 'A ');
Fwrite ($ res, $ file );
Fclose ($ res );
Return "{'filename': $ fileName, 'savedir': $ dirName }";
}
// Example
// Return value: {'filename': 13668030896.jpg, 'savedir':/www/test/img/2013/04/24