views:

330

answers:

2

Hi,

I am a PHP newbie and trying to add a progress-bar to an existing PHP script using the following method :

$ch=curl_init() or die("ERROR|<b>Error:</b> cURL Error");
curl_setopt($ch, CURLOPT_URL, $c);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_FILE, $fp);

//####################################################//
// This is required to curl give us some progress
// if this is not set to false the progress function never
// gets called
curl_setopt($ch, CURLOPT_NOPROGRESS, false);

// Set up the callback
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'callback');

// Big buffer less progress info/callbacks
// Small buffer more progress info/callbacks
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
//####################################################//

curl_exec($ch);
curl_close($ch);
fclose($fp);

The callback function :

    function callback($download_size, $downloaded, $upload_size, $uploaded)
{
    $percent=$downloaded/$download_size;
  // Do something with $percent
  echo "$percent";      
}

Now, I had literally copy-pasted this example from PHP site but this is not working ?? My PHP version is 5.2.11, Pls. suggest what could be wrong ??

Edit : I am calling this php script from another script.

Information : I am stuck with 5.2.X branch as my web-host says cPanel does not support the 5.3.x branch yet, any solutions for this ??

+5  A: 

There doesn't seem to be a CURLOPT_PROGRESSFUNCTION before php 5.3.

Take a look at http://cvs.php.net/viewvc.cgi/php-src/ext/curl/interface.c?view=log and you will find two entries - [DOC] MFH: #41712, implement progress callback. One for the php5.3 and one for the php6 branch.

edit: With php 5.2.x you should be able to set a stream_notification_callback

function foo() {
  $args = func_get_args();
  echo join(', ', $args), "\n";
}

$ctx = stream_context_create(null, array('notification' =>'foo'));
$fpIn = fopen('http://php.net/', 'rb', false, $ctx);
file_put_contents('localfile.txt', $fpIn);
VolkerK
Thanks, I will ask my host to update php and see if this works.
I am stuck with 5.2.X branch as my web-host says cPanel does not support the 5.3.x branch yet, any solutions for this ??
By the way, don't forget to `flush` after you echo: php.net/manual/en/function.ob-flush.php
Pekka
If not using curl is acceptable the stream api offers notification callback, too. And they are available sincee php 5.2. see edit.
VolkerK
A: 

Regarding the last comment, said code requires 5.3 because stream_context_create()'s second parameter was added in 5.3. However, replacing that line with the following works in 5.2:

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

And in related news, the stream_notification_callback() documentation within the PHP manual has an example that fully utilizes/creates a progress bar, so check it out.

http://php.net/stream_notification_callback

philip