Skip to content

Instantly share code, notes, and snippets.

@oleteacher
Forked from stuudmuffin/curl_progress.php
Last active February 6, 2021 23:30
Show Gist options
  • Save oleteacher/989752627783b9a06ab39cd914b40e8b to your computer and use it in GitHub Desktop.
Save oleteacher/989752627783b9a06ab39cd914b40e8b to your computer and use it in GitHub Desktop.
PHP/cURL File Download with Progress Bar #curl
<?php
//output buffer
ob_start();
//create javascript progress bar
echo '<html><head>
<script type="text/javascript">
function updateProgress(percentage) {
document.getElementById(\'progress\').value = percentage;
}
</script></head><body>
<progress id="prog" value="0" max="100.0"></progress>
';
//initilize progress bar
ob_flush();
flush();
//save progress to variable instead of a file
$temp_progress = '';
$targetFile = fopen( 'testfile.iso', 'w' );
$ch = curl_init( 'http://ftp.free.org/mirrors/releases.ubuntu-fr.org/11.04/ubuntu-11.04-desktop-i386-fr.iso' );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_NOPROGRESS, false );
curl_setopt( $ch, CURLOPT_PROGRESSFUNCTION, 'progressCallback' );
curl_setopt( $ch, CURLOPT_FILE, $targetFile );
curl_exec( $ch );
fclose( $targetFile );
//must add $resource to the function after a newer php version. Previous comments states php 5.5
function progressCallback( $resource, $download_size, $downloaded_size, $upload_size, $uploaded_size )
{
static $previousProgress = 0;
if ( $download_size == 0 ) {
$progress = 0;
} else {
$progress = round( $downloaded_size * 100 / $download_size );
}
if ( $progress > $previousProgress)
{
$previousProgress = $progress;
$temp_progress = $progress;
}
//update javacsript progress bar to show download progress
echo '<script>document.getElementById(\'prog\').value = '.$progress.';</script>';
ob_flush();
flush();
//sleep(1); // just to see effect
}
//if we get here, the download has completed
echo "Done";
//flush just to be sure
ob_flush();
flush();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment