How to download a file with PHP

0

Hello and Happy New Year for all

Today I have a question as I can make a script to download a file from a url and change the name of the file with php this is my code I hope you help me and thanks

<?php

$headers = "https://r8---sn-0opoxu-gxml.googlevideo.com/videoplayback?signature=289B43A5B01E7928A020EC2DDB921E61972D217A.6872F3E478AEFF627E06D93BBBF0610B870A2887&source=youtube&clen=5920214&expire=1514879772&initcwndbps=306250&itag=17&key=yt6&ei=vOZKWutvg8a4BcfanqgG&sparams=clen,dur,ei,gir,id,initcwndbps,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pl,requiressl,source,usequic,expire&mn=sn-0opoxu-gxml&mm=31&ip=187.195.231.38&dur=593.780&id=o-AF9C8zlg_rItNY5MwJb5pg3J8q40F3RcUzKMFsddxZkx&mime=video/3gpp&ms=au&requiressl=yes&pl=19&mv=m&mt=1514858069&usequic=no&gir=yes&ipbits=0&lmt=1514857104023208";
$url= basename($headers);
$fileName = 'video.3gp';
if(!empty($url)){
    // Define headers
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$fileName");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // Read the file
    readfile($fileName);
    exit;
}else{
    echo 'error';
}
?>
    
asked by Shareiv 02.01.2018 в 03:14
source

1 answer

2

If you generate a file from your own server internally, your example could be useful, but if you want to download an external file and rename it you can use the following example:

<?php
$nuevo_nombre = 'nuevo_nombre'; //asignamos nuevo nombre
$archivo_descarga = curl_init(); //inicializamos el curl
curl_setopt($archivo_descarga, CURLOPT_URL, 'http://pluspng.com/img-png/php-384.png'); //ponemos lo que queremos descargar
//curl_setopt($archivo_descarga, CURLOPT_HEADER, true);
curl_setopt($archivo_descarga, CURLOPT_RETURNTRANSFER, true);
curl_setopt($archivo_descarga, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($archivo_descarga, CURLOPT_AUTOREFERER, true);
$resultado_descarga = curl_exec($archivo_descarga); //realizamos la descarga
if(!curl_errno($archivo_descarga)) // si no hay error hacemos la descarga
{
  header('Content-type:image/png'); //Acá le cambias el tipo de archivo (MimeType) por lo que quieras
  header('Content-Disposition: attachment; filename ="'.$nuevo_nombre.'.png"'); //renombramos la descarga
  echo($resultado_descarga);
  exit();
}else
{
  echo(curl_error($archivo_descarga)); // Si hay error lo mostramos
}
?> 

To make the previous example work, you must have the active cURL extension. If you do not know how to activate it, find out how to activate cURL in php on the internet.

It is better to do so, since it is better to enable that extension than to be modifying sensitive configurations of your server that could put you at risk.

Take a tour around here so you can see the available options of the cURL extension: link

    
answered by 03.01.2018 / 05:51
source