


Curl download file displays real-time progress bar (with code)
This time I will bring you a real-time progress bar display for Curl download files (with code). What are the precautions for Curl download files to display a real-time progress bar? The following is a practical case, let's take a look.
Preface
Recently, I have been tinkering with programming under the command line. Downloading files is always an arduous process. It would be much better if there was a progress bar. Got it! ! !
Let’s start with a progress bar expansion package, which is pretty goodhttps://github.com/dariuszp/cli-progress-bar (local download)
Rendering:
It’s still pretty good-looking!
What is the use of curl?
Use php, curl mainly captures data, of course we can use other methods to capture, For example, fsockopen, file_get_contents, etc. But it can only capture those pages that can be directly accessed. If you want to capture pages with page Access Control, or pages after logging in, it will be more difficult.
curl uses
curl as a very common download method for PHP, here is a simple way to use it;
// 初始化一个 curl $ch = curl_init(); // 设置请求的 url curl_setopt($ch, CURLOPT_URL, $url); // curl_setopt($ch, CURLOPT_HEADER, 0); // 不直接输出,而是通过 curl_exec 返回 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if (false === ($stream = curl_exec($ch))) { throw new \Exception(curl_errno($ch)); } curl_close($ch); return $stream;
The above is a very simple example. If a file is large, the user will need to wait for a long time. At this time, we should add the effect of the progress bar:
class Request { protected $bar; // 是否下载完成 protected $downloaded = false; public function construct() { // 初始化一个进度条 $this->bar = new CliProgressBar(100); $this->bar->display(); $this->bar->setColorToRed(); } function download($url) { $ch = curl_init(); // 从配置文件中获取根路径 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // 开启进度条 curl_setopt($ch, CURLOPT_NOPROGRESS, 0); // 进度条的触发函数 curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progress'); // ps: 如果目标网页跳转,也跟着跳转 // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); if (false === ($stream = curl_exec($ch))) { throw new \Exception(curl_errno($ch)); } curl_close($ch); return $stream; } /** * 进度条下载. * * @param $ch * @param $countDownloadSize 总下载量 * @param $currentDownloadSize 当前下载量 * @param $countUploadSize * @param $currentUploadSize */ public function progress($ch, $countDownloadSize, $currentDownloadSize, $countUploadSize, $currentUploadSize) { // 等于 0 的时候,应该是预读资源不等于0的时候即开始下载 // 这里的每一个判断都是坑,多试试就知道了 if (0 === $countDownloadSize) { return false; } // 有时候会下载两次,第一次很小,应该是重定向下载 if ($countDownloadSize > $currentDownloadSize) { $this->downloaded = false; // 继续显示进度条 } // 已经下载完成还会再发三次请求 elseif ($this->downloaded) { return false; } // 两边相等下载完成并不一定结束, elseif ($currentDownloadSize === $countDownloadSize) { return false; } // 开始计算 $bar = $currentDownloadSize / $countDownloadSize * 100; $this->bar->progress($bar); } } (new Request)->download('http://www.shiguopeng.cn/database.sql');
Be sure to pay attention to the download callback There is a pitfall in judgment! ! !
There is another problem: if you jump to download and set curl to jump, the returned file will have problems.
I downloaded a zip file, which will cause the file header There is the content of the HTTP response header of the first request,
So you need to see what you needcurl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
I believe you have read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the steps to dynamically add XML data with PHP
CMSPRESS implements unlimited classification (with code)
The above is the detailed content of Curl download file displays real-time progress bar (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

When you click the search field in Windows 11, the search interface automatically expands. It displays a list of recent programs on the left and web content on the right. Microsoft displays news and trending content there. Today's check promotes Bing's new DALL-E3 image generation feature, the "Chat Dragons with Bing" offer, more information about dragons, top news from the Web section, game recommendations, and the Trending Search section. The entire list of items is independent of your activity on your computer. While some users may appreciate the ability to view news, all of this is abundantly available elsewhere. Others may directly or indirectly classify it as promotion or even advertising. Microsoft uses interfaces to promote its own content,

Microsoft's Windows 11 operating system may periodically display suggestions as pop-ups on your computer using the notification system. The suggestions system, originally intended to provide users with tips and suggestions for improving their Windows 11 workflows, has almost completely transformed into an advertising system to promote Microsoft services and products. Suggestion pop-ups might advertise a Microsoft 365 subscription to users, suggest linking an Android phone to the device, or set up a backup solution. If these pop-ups annoy you, you can tweak your system to disable them entirely. The following guide provides recommendations on disabling pop-ups on devices running Microsoft’s Windows 11 operating system.

To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

How to handle 301 redirection of web pages in PHPCurl? When using PHPCurl to send network requests, you will often encounter a 301 status code returned by the web page, indicating that the page has been permanently redirected. In order to handle this situation correctly, we need to add some specific options and processing logic to the Curl request. The following will introduce in detail how to handle 301 redirection of web pages in PHPCurl, and provide specific code examples. 301 redirect processing principle 301 redirect means that the server returns a 30

What happens when the desktop layout is locked? When using the computer, sometimes we may encounter the situation where the desktop layout is locked. This problem means that we cannot freely adjust the position of desktop icons or change the desktop background. So, what exactly is going on when it says that the desktop layout is locked? 1. Understand the desktop layout and locking functions. First, we need to understand the two concepts of desktop layout and desktop locking. Desktop layout refers to the arrangement of various elements on the desktop, including shortcuts, folders, widgets, etc. we can be free

Utilizing C++ to implement real-time audio and video processing functions of embedded systems The application range of embedded systems is becoming more and more extensive, especially in the field of audio and video processing, where the demand is growing. Faced with such demand, using C++ language to implement real-time audio and video processing functions of embedded systems has become a common choice. This article will introduce how to use C++ language to develop real-time audio and video processing functions of embedded systems, and give corresponding code examples. In order to realize the real-time audio and video processing function, you first need to understand the basic process of audio and video processing. Generally speaking, audio and video

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We
