PHP Using CURL to Download File Function Example

  • 2021-12-11 17:24:36
  • OfStack

In this paper, an example is given to show that PHP uses CURL to realize the function of downloading files. Share it for your reference, as follows:

If you use CURL to download pictures uploaded from WeChat mobile phone? Refer to the following code


/**
 * CURL Download a file   Success returns file name, failure returns false
 * @param $url
 * @param string $savePath
 * @return bool|string
 * @author Zou Yiliang
 */
public function downFile($url, $savePath = './uploads')
{
  //$url = 'http://www.baidu.com/img/bdlogo.png';
  /*
  HTTP/1.1 200 OK
  Connection: close
  Content-Type: image/jpeg
  Content-disposition: attachment; filename="cK4q4fLsp7YOlaqxluDOafB.jpg"
  Date: Sun, 18 Jan 2015 16:56:32 GMT
  Cache-Control: no-cache, must-revalidate
  Content-Length: 963704
  */
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, TRUE);  // Need response header
  curl_setopt($ch, CURLOPT_NOBODY, FALSE);  // Need response body
  $response = curl_exec($ch);
  // Separate header And body
  $header = '';
  $body = '';
  if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') {
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); // Header information size
    $header = substr($response, 0, $headerSize);
    $body = substr($response, $headerSize);
  }
  curl_close($ch);
  // Filename 
  $arr = array();
  if (preg_match('/filename="(.*?)"/', $header, $arr)) {
    $file = date('Ym') . '/' . $arr[1];
    $fullName = rtrim($savePath, '/') . '/' . $file;
    // Create a directory and set permissions 
    $basePath = dirname($fullName);
    if (!file_exists($basePath)) {
      @mkdir($basePath, 0777, true);
      @chmod($basePath, 0777);
    }
    if (file_put_contents($fullName, $body)) {
      return $file;
    }
  }
  return false;
}

Attachment: Description of commonly used CURL options

CURLOPT_AUTOREFERER
When redirected according to Location:, the Referer: information in header is automatically set.

CURLOPT_BINARYTRANSFER
When CURLOPT_RETURNTRANSFER is enabled, the native (Raw) output is returned.

CURLOPT_COOKIESESSION
When enabled, curl will only pass one session cookie, ignoring other cookie. By default, cURL will return all cookie to the server. session cookie refers to those cookie that are used to determine whether the server-side session is valid or not.

CURLOPT_CRLF
Converts Unix newline characters to carriage return newline characters when enabled.

CURLOPT_DNS_USE_GLOBAL_CACHE
When enabled, 1 global DNS cache is enabled, which is thread safe and is enabled by default.

CURLOPT_FAILONERROR
Displays the HTTP status code, and the default behavior is to ignore HTTP messages with numbers less than or equal to 400.

CURLOPT_FILETIME
When enabled, it attempts to modify the information in the remote document. The result information is returned through the CURLINFO_FILETIME option of the curl_getinfo () function. curl_getinfo ().

CURLOPT_FOLLOWLOCATION
When enabled, the "Location:" returned by the server is recursively returned to the server in header, and the number of recursive returns can be limited by using CURLOPT_MAXREDIRS.

CURLOPT_FORBID_REUSE
Forced disconnection after interaction is completed and cannot be reused.

CURLOPT_FRESH_CONNECT
Force a new connection to replace the connection in the cache.

CURLOPT_FTP_USE_EPRT
When enabled, use the EPRT (or LPRT) command when FTP is downloaded. Disable EPRT and LPRT when set to FALSE, using the PORT command only.

CURLOPT_FTP_USE_EPSV
When enabled, try the EPSV command first before reverting to PASV mode during FTP transmission. Disable the EPSV command when set to FALSE.

CURLOPT_FTPAPPEND
When enabled, append the write file instead of overwriting it.

CURLOPT_FTPASCII
Alias for CURLOPT_TRANSFERTEXT.

CURLOPT_FTPLISTONLY
Only the name of the FTP directory is listed when enabled.

CURLOPT_HEADER
When enabled, the information of the header file is output as a data stream.

CURLINFO_HEADER_OUT
Trace the request string of the handle when enabled.
Available from PHP 5.1. 3. The CURLINFO_ prefix is intentional (intentional).

CURLOPT_HTTPGET
When enabled, method of HTTP is set to GET, because GET is the default, so it is only used if it is modified.

CURLOPT_HTTPPROXYTUNNEL
When enabled, it is transmitted through the HTTP proxy.

CURLOPT_MUTE
When enabled, all modified parameters in the cURL function are restored to their default values.

CURLOPT_NETRC
After the connection is established, access the ~/. netrc file for user name and password information to connect to the remote site.

CURLOPT_NOBODY
When enabled, the BODY part of HTML will not be output.

CURLOPT_NOPROGRESS
Close the progress bar of curl transport when enabled, and the default setting of this item is enabled.
Note:
PHP automatically sets this option to TRUE, which should only be changed for debugging purposes.

CURLOPT_NOSIGNAL
Ignore all curl to php signals when enabled. This item is enabled by default during SAPI multithreaded transfer.
cURL was added at 7.10.

CURLOPT_POST
When enabled, a regular POST request of type application/x-www-form-urlencoded is sent, just like 1 for form submission.

CURLOPT_PUT
When enabled, HTTP is allowed to send files, and both CURLOPT_INFILE and CURLOPT_INFILESIZE must be set.

CURLOPT_RETURNTRANSFER
The information obtained by curl_exec () is returned as a file stream instead of being output directly.

CURLOPT_SSL_VERIFYPEER
When disabled, cURL terminates authentication from the server. Use the CURLOPT_CAINFO option to set certificates Use the CURLOPT_CAPATH option to set the certificate directory If CURLOPT_SSL_VERIFYPEER (default 2) is enabled, CURLOPT_SSL_VERIFYHOST needs to be set to TRUE or FALSE.
Default to TRUE from cURL 7.10. Start the default binding installation from cURL 7.10.

CURLOPT_TRANSFERTEXT
Use ASCII mode for FTP transport when enabled. For LDAP, it retrieves plain text information instead of HTML. On an Windows system, the system does not set STDOUT to binary mode.

CURLOPT_UNRESTRICTED_AUTH
User name and password information is continuously appended to a plurality of locations in an header generated using CURLOPT_FOLLOWLOCATION, even if the domain name has changed.

CURLOPT_UPLOAD
Enable file upload.

CURLOPT_VERBOSE
When enabled, all information is reported and stored in STDERR or the specified CURLOPT_STDERR.

PS: For specific curl parameter description, please refer to: https://www. ofstack. com/article/39331. htm

For more readers interested in PHP related contents, please check the topics of this site: "php curl Usage Summary", "PHP Network Programming Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "PHP Data Structure and Algorithm Tutorial" and "json Format Data Operation Skills Summary in PHP"

I hope this article is helpful to everyone's PHP programming.


Related articles: