简体   繁体   中英

If statements inside PHP Curl Writefunction

In my function here I am trying to perform functions when files are downloaded past certain milestones. So in this instance I want to download 10mb, then echo milestone, then repeat again to the next 10mb.

The file I'm downloading is about 300mb, so I'd expect the function to be called 30 times.

What does milestone need to be? bytes? kilobytes? Whatever it is, if I go beyond about 10000, it no longer calls anything inside that if.

curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $chunk) {
$chunksize = strlen($chunk);
$downloaded .= $chunksize;
if($downloaded > $milestone){
    echo "milestone";
    $downloaded = 0;
}
return $chunksize;
});

Just gonna guess that the real problem is that the variables $downloaded and $milestone are not in scope in this function and/or are reset every time the function executes. You'll probably want to make $downloaded static and include $milestone from the surrounding scope:

$milestone = /* something */;

curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) use ($milestone) {
    static $downloaded = 0;

    $chunksize = strlen($chunk);
    $downloaded .= $chunksize;
    if ($downloaded > $milestone){
        echo "milestone";
        $downloaded = 0;
    }
    return $chunksize;
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM