Here is my function:
curl_setopt( $curl, CURLOPT_PROGRESSFUNCTION, function ( $resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) use ($array)
{
static $previousProgress = 0;
if ( $download_size == 0 ) {
$progress = 0;
} else {
$progress = round( $downloaded_size * 100 / $download_size );
}
As you can see I'm inserting my own variables with use
at the end of the function.
What I'm trying to do is simply echo this line ONCE after the else
condition
echo ' ' . $progress . '%' . ' (' . bytes($downloaded_size) . ' of ' . bytes($download_size) . ') ';
I've tried things such as
static $previousProgress = 0;
$count = $previousProgress++;
} else {
if ($count == 1) { echo echo ' ' . $progress . '%' . ' (' . bytes($downloaded_size) . ' of ' . bytes($download_size) . ') '; }
$progress = round( $downloaded_size * 100 / $download_size );
}
But at this point the function has already ran an unknown amount of times (50, or 60 sometimes), before it hits the else
condition.
I can of course do this
static $previousProgress = 0;
$count = $previousProgress++;
if ($count == 1) { echo ' ' . $progress . '%' . ' (' . bytes($downloaded_size) . ' of ' . bytes($download_size) . ') '; }
And it works to only echo once.. but the issue is CURL
does not have the $downloaded_size
or $download_size
variables set and display as 0 bytes
- therefore it needs to be in the else condition.
I've tried using true
/ false
variables as one would normally do to output something once in a for
or foreach
loop, but since the function is just recursively running until it times out, the function starts over again and this does not work.
As I said, I can insert an array of variables into this function to help me... but I'm not sure how I can do this considering the function starts over and is re-run everytime..
Tried other random things but I am apparently missing something. How can I echo the download size only once in the repeating function?
A static boolean variable should do what you want.
static $firstTime = true;
if ($firstTime) {
echo "something";
$firstTime = false;
}
The problem with your code is probably because you were using post-increment. If $previousProgress
is 0
, the line:
$count = $previousProgress++;
will set $count
to 0
(the old value) while incrementing $previousProgress
to 1
. So the if ($count == 1)
condition wasn't true until the second iteration. If you used ++$previousProgress
it would set them both to 1
. That's the difference between pre-increment and post-increment.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.