Home > Backend Development > PHP Tutorial > Efficiency improvement: Sharing of development skills for PHP asynchronous HTTP download of multiple files

Efficiency improvement: Sharing of development skills for PHP asynchronous HTTP download of multiple files

WBOY
Release: 2023-09-12 12:38:01
Original
1050 people have browsed it

效率提升:PHP 异步 HTTP 下载多个文件的开发技巧分享

Efficiency improvement: Sharing development skills for PHP asynchronous HTTP downloading of multiple files

In modern Internet applications, file downloading is a very common requirement. However, when a large number of files need to be downloaded, the traditional synchronous download method is often inefficient, causing users to wait for a long time and reducing the user experience. This article will introduce a development technique for using PHP asynchronous HTTP to download multiple files to improve download efficiency and user experience.

  1. The principle of asynchronous HTTP download
    The traditional synchronous download method is to download files one by one and wait for the previous file to be downloaded before downloading the next file. Asynchronous HTTP downloads can initiate multiple requests at the same time, making full use of network bandwidth and greatly improving download speed. The cURL extension library can be used in PHP to implement asynchronous HTTP requests.
  2. Use cURL to implement asynchronous HTTP download
    First, make sure your server has the cURL extension library installed. In PHP, asynchronous HTTP requests can be implemented through the following code:
$urls = array(
  'http://example.com/file1.zip',
  'http://example.com/file2.zip',
  'http://example.com/file3.zip',
  // 添加更多文件链接
);

$mh = curl_multi_init();
$handles = array();

foreach ($urls as $url) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_multi_add_handle($mh, $ch);
  $handles[] = $ch;
}

$running = null;
do {
  curl_multi_exec($mh, $running);
} while ($running > 0);

foreach ($handles as $ch) {
  curl_multi_remove_handle($mh, $ch);
  curl_close($ch);
}

curl_multi_close($mh);
Copy after login

The above code first defines the file link that needs to be downloaded, and then initializes a cURL multiprocessing handle. Loop through the file links, creating a cURL handle for each link and adding it to the multiprocessing handle. Subsequently, all requests are executed by calling the curl_multi_exec() function until no requests are running. Finally, clean up resources and close cURL handles and multiprocessing handles.

  1. Processing download results
    In the above asynchronous HTTP download code, whether it is successful or failed, the download result will be ignored. In order to better handle the download results, you can obtain the information of each request through the curl_multi_info_read() function. The following is a sample code:
$completed = 0;
do {
  $mh = curl_multi_init();
  $handles = array();

  foreach ($urls as $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($mh, $ch);
    $handles[] = $ch;
  }

  $running = null;
  do {
    curl_multi_exec($mh, $running);
    $info = curl_multi_info_read($mh);
    if ($info !== false) {
      // 处理下载结果
      $completed++;
      $handle = $info['handle'];
      // ...
    }
  } while ($running > 0);

  foreach ($handles as $ch) {
    curl_multi_remove_handle($mh, $ch);
    curl_close($ch);
  }

  curl_multi_close($mh);
} while ($completed < count($urls));
Copy after login

In the above code, after each asynchronous HTTP request is executed, the curl_multi_info_read() function is used to check whether any request has been completed. If there is a completed request, the relevant download result information can be obtained from the returned information and processed accordingly. By recording the number of completed requests, you can determine whether all requests have been completed.

  1. Add error handling
    In actual use, abnormal situations such as network connection errors or server response errors may occur. In order to handle these exceptions, you can add corresponding error handling code in the settings of each request to ensure the stability and reliability of the download.
foreach ($urls as $url) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  // 添加错误处理
  curl_setopt($ch, CURLOPT_FAILONERROR, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);

  curl_multi_add_handle($mh, $ch);
  $handles[] = $ch;
}
Copy after login

In the above code, by setting the CURLOPT_FAILONERROR option to true, you can throw an exception when the request fails. At the same time, by setting reasonable CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT options, you can set the connection and request timeout to avoid download failures caused by timeout.

Summary
The technique of using PHP asynchronous HTTP to download multiple files can greatly improve download efficiency and user experience. By properly using the cURL extension library, multiple HTTP requests can be initiated simultaneously to maximize the use of network bandwidth. At the same time, abnormal situations are handled reasonably to ensure the stability and reliability of downloads. Through these development skills, we can handle the download requirements of large amounts of files more efficiently in actual projects.

The above is the detailed content of Efficiency improvement: Sharing of development skills for PHP asynchronous HTTP download of multiple files. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template