A function implemented by PHP to save remote files to a local device,
Recently, I encountered a PHP Remote Image local problem. I checked the manual and found that file_get_contents () and file_put_contents () can solve this problem. The idea is simple. Read remote files into strings and write them to the specified directory according to the rules. This method can collect images, text files, audio files, and so on, as long as you can find a way to get their addresses.
First run the Code:
Copy codeThe Code is as follows:
/**
* Save the file to a local device.
* @ Param file path $ url
* @ Param Save the local path $ savePath
* @ Return string
*/
Function downloadFile ($ url, $ savePath = '')
{
$ FileName = getUrlFileExt ($ url );
$ FileName = rand (0,1000). $ fileName;
$ File = file_get_contents ($ url );
File_put_contents ($ savePath. '/'. $ fileName, $ file );
Return $ fileName;
}
/**
* Get the file extension
* @ Param webpage URL $ url
* @ Return string
*/
Function getUrlFileExt ($ url)
{
$ Ary = parse_url ($ url );
$ File = basename ($ ary ['path']);
$ Ext = explode ('.', $ file );
Return $ ext [1];
}
Example:
Copy codeThe Code is as follows:
DownloadFile ("http://blog.jb51.net/wp-content/themes/inove/img/mei.png", "/upload/2012/01 /")
The file_get_contents (path) function is the same as the file () function. The difference is that file_get_contents () reads the file into a string. Path is a required parameter that specifies the file to be read.
The file_put_contents (file, data) function writes a string to a file. It is the same as calling the fopen (), fwrite (), and fclose () functions in turn. File is a required parameter that specifies the file to write data. If the file does not exist, create a new file. Data is the data to be written. It can be a string, array, or data stream.
Parse_url () can capture the analysis url Information. Here we use it to obtain the file name.
Official example:
Copy codeThe Code is as follows:
$ Php-r 'print _ r (parse_url ("http: // invalid_host .. name /"));'
Array
(
[Scheme] => http
[Host] => invalid_host... name
[Path] =>/
)