Use Curl to download network images

Source: Internet
Author: User
When using open API interfaces such as sina and tencent, you need to save the user's profile picture. in the specific implementation process, we compared the two methods, and finally chose the CURL method to be read by CURL.

This is required to enable CURL extension before use. Tip: It seems that the CURL extension cannot be installed in a version of php 5.2.****. this is a bug.

function save_img_curl($avatar_url) {  $res = curl_init($avatar_url);  ob_start();  curl_exec($res);  $avatar_file = ob_get_contents();  ob_end_clean();  $info = curl_getinfo($res);  curl_close($res);  echo $info['total_time']."\n";  // save avatar  $up_dir = "./img/";  if (!is_dir($up_dir))  {   @mkdir($up_dir, 0777);  }   $avatar_name = time().'.jpg';  $handle = fopen($up_dir.$avatar_name, 'a');  fwrite($handle, $avatar_file);  fclose($handle);  return; } 

Note: I directly use .jpg as the extension. In fact, it depends on $ info ['content-type.

Readfile method
function save_img_curl($avatar_url) {  $time_start = time();  ob_start();   readfile($avatar_url);  $avatar_file = ob_get_contents();  ob_end_clean();  $time_end = time();  echo "\n".$time_end-$time_start."\n"; } 
Comparison & doubt

The CURL method is used to compare the two methods, and you have some questions:

  • The two methods are similar when reading sina images, but they differ greatly when reading qq images. why?
  • Retrieving sina images is always much faster than qq images. is it related to the Internet? But the gap is too big.

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.