Last active
October 4, 2023 09:12
-
-
Save motebaya/23c7b81fabd9ecf1b00e4c6dbff1f6f7 to your computer and use it in GitHub Desktop.
php download progress bar with guzzlehttp & symfony/console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include "./vendor/autoload.php"; | |
use \GuzzleHttp\Client; | |
use \Symfony\Component\Console\Helper\ProgressBar; | |
use \Symfony\Component\Console\Output\ConsoleOutput; | |
/** | |
* https://stackoverflow.com/questions/15188033/human-readable-file-size | |
* https://symfony.com/doc/current/components/console/helpers/progressbar.html | |
*/ | |
function human_size(int $length) | |
{ | |
$sizes = ['B', 'KB', 'MB', 'GB', 'TB']; | |
$i = (int) floor(log($length, 1024)); | |
return sprintf( | |
"%s %s", | |
round($length / (1024 ** $i), 2), | |
$sizes[$i] | |
); | |
} | |
function download($url) | |
{ | |
$filename = explode("/", $url); | |
$fullpath = end($filename); | |
$progress = new ProgressBar(new ConsoleOutput(), 50); | |
$progress->setFormat('%message%: %downloaded%/%total% %bar% %percent:3s%% eta %estimate%'); | |
$progress->setMessage($fullpath, 'message'); | |
$progress->setBarCharacter("\033[32m━\033[0m"); | |
$progress->setEmptyBarCharacter("\033[90m━\033[0m"); | |
$progress->setProgressCharacter("\033[30m╸\033[0m"); | |
(new Client())->request("GET", $url, [ | |
'sink' => $fullpath, | |
'progress' => function (int $download_size, int $downloaded) use ($progress) { | |
$progress->setMaxSteps($download_size); | |
$progress->setProgress($downloaded); | |
$progress->setMessage(human_size($downloaded), 'downloaded'); | |
$progress->setMessage(human_size($download_size), 'total'); | |
$progress->setMessage( | |
gmdate( | |
"H:i:s", | |
$progress->getEstimated() | |
), | |
"estimate" | |
); | |
} | |
]); | |
$progress->finish(); | |
print "\n"; | |
} | |
$batch = [ | |
"https://images8.alphacoders.com/131/1313894.jpeg", # 2.MB | |
"https://w.wallhaven.cc/full/28/wallhaven-28wzyy.jpg", # 5.9MB | |
"http://speedtest.ftp.otenet.gr/files/test100k.db", | |
"http://speedtest.ftp.otenet.gr/files/test1Mb.db" | |
]; | |
foreach ($batch as $url) { | |
download($url); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here i'm still researching and trying to find out how to make the progress work with multithreadpool. cuz i think it's need more fast.