PHP downloads remote images to the local device through URLs

Source: Internet
Author: User

In this article, an ajax instance provides a section about saving an image to the local address through the image address. Here we can directly read the image through readfile and save it through fopen.

Instance

The Code is as follows: Copy code

<? Php
/**
* Download the image to the local device through the remote url of the image
* @ Param: $ url indicates the remote link of the image.
* @ Param: $ filename indicates the file name saved after the image is downloaded.
*/
Function GrabImage ($ url, $ filename ){
If ($ url = ""): return false; endif;
 
Ob_start ();
Readfile ($ url );
$ Img = ob_get_contents ();
Ob_end_clean ();
$ Size = strlen ($ img );
 
// "../Images/books/" is the storage directory, and $ filename is the file name.
$ Fp2 = @ fopen (".../../images/books/". $ filename, "");
Fwrite ($ fp2, $ img );
Fclose ($ fp2 );
 
Return $ filename;
}
?>

The function returns the name saved after the image is downloaded. You only need to store the image directory + image name in the database.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.