Question:
I'm having some issues with the script
process below.
Literally it's downloading very slowly, and that's when the download process doesn't crash or restart from scratch.
Is there any way to fix this so that the download is done normally, with a more efficient process?
The files for download reach a maximum of 350MB
.
Update: Someone could tell me what the problem is I have already changed in php.ini the parameter settings of memory_limit
, post_max_size
, upload_max_filesize
and max_execution_time
and even so the download process is still slow.
<?php
$file = 'http://thumb.mais.uol.com.br/15540367.mp4';
download($file,314572800);
function download($file,$chunks){
set_time_limit(0);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-disposition: attachment; filename='.basename($file));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
$size = get_size($file);
header('Content-Length: '.$size);
$i = 0;
while($i<=$size){
get_chunk($file,(($i==0)?$i:$i+1),((($i+$chunks)>$size)?$size:$i+$chunks));
$i = ($i+$chunks);
}
}
function chunk($ch, $str) {
print($str);
return strlen($str);
}
function get_chunk($file,$start,$end){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_RANGE, $start.'-'.$end);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'chunk');
$result = curl_exec($ch);
curl_close($ch);
}
function get_size($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
return intval($size);
}
?>
Answer:
//Tempo de execução ilimitado, visto que você
//baixará arquivos grandes
set_time_limit(0);
/*Ponteiro do Curl*/
$ch = curl_init();
/*Ponteiro do arquivo que será salvo*/
$fp = fopen($destino, "w");
/*Configuração*/
$options = [
CURLOPT_RETURNTRANSFER => true, //preciso da resposta armazenada
CURLOPT_TIMEOUT => 120, // limite de 120 segundos
CURLOPT_URL => $url, //recurso a ser procurado
CURLOPT_FILE => $fp, //ponteiro do arquivo
CURLOPT_HEADER => false, //Para não corromper o arquivo
];
/*Aplica a configuração*/
curl_setopt_array($ch, $options);
/*Baixa o arquivo*/
curl_exec($ch);
/*Fecha o ponteiro do arquivo*/
fclose($fp);
/*Fecha o Curl*/
curl_close($ch);