cURL download progress in PHP

后端 未结 3 1924
我在风中等你
我在风中等你 2020-11-27 05:48

I\'m pretty new to cURL so I\'ve been struggling with this one for hours. I\'m trying to download the source of a website in an iframe using cURL and while it\'s loading to

3条回答
  •  孤独总比滥情好
    2020-11-27 06:15

    This is how the callback looks in C:

    typedef int (*curl_progress_callback)(void *clientp,
                                          double dltotal,
                                          double dlnow,
                                          double ultotal,
                                          double ulnow);
    

    Probably in PHP it should look like

    curl_progress_callback($clientp, $dltotal, $dlnow, $ultotal, $ulnow)
    

    So, assuming you have page.html which loads a .php file in an iframe.

    In your php script, you will require the following functions:

    curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, 'curl_progress_callback');    
    curl_setopt($curl, CURLOPT_BUFFERSIZE,64000);    
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    

    which should produce an output similar to the following:

    0
    0.1
    0.2
    0.2
    0.3
    0.4
    ...
    

    then on the iframe page, you will have a progress bar

    0%

    CSS would be something like this

    #progress-bar {
        width: 200px;
        padding: 2px;
        border: 2px solid #aaa;
        background: #fff;
    }
    
    #progress {
        background: #000;
        color: #fff;
        overflow: hidden;
        white-space: nowrap;
        padding: 5px 0;
        text-indent: 5px;
        width: 0%;
    }
    

    The javascript

    var progressElement = document.getElementById('progress')
    
    function updateProgress(percentage) {
        progressElement.style.width = percentage + '%';
        progressElement.innerHTML = percentage + '%';
    }
    

    You can have it output JavaScript and have it update the progress bar for you, for example:

    
    
    
    

    You might be interested in some more example code

提交回复
热议问题