web-dev-qa-db-fra.com

Télécharger le fichier sur le serveur à partir de l'URL

Eh bien, celui-ci semble assez simple, et il l'est. Tout ce que vous avez à faire pour télécharger un fichier sur votre serveur est:

file_put_contents("Tmpfile.Zip", file_get_contents("http://someurl/file.Zip"));

Seulement il y a un problème. Et si vous avez un fichier volumineux, comme 100 Mo. Ensuite, vous manquerez de mémoire et ne pourrez pas télécharger le fichier.

Ce que je veux, c'est un moyen d'écrire le fichier sur le disque au fur et à mesure que je le télécharge. De cette façon, je peux télécharger des fichiers plus volumineux sans rencontrer de problèmes de mémoire.

315
xaav

Depuis PHP 5.1.0, file_put_contents() permet d'écrire pièce par pièce en transmettant un descripteur de flux en tant que paramètre $data:

file_put_contents("Tmpfile.Zip", fopen("http://someurl/file.Zip", 'r'));

Du manuel:

Si les données [c'est le deuxième argument] est une ressource de flux, le tampon restant de ce flux sera copié dans le fichier spécifié. Ceci est similaire avec stream_copy_to_stream() .

(Merci Hakre .)

459
alex
private function downloadFile($url, $path)
{
    $newfname = $path;
    $file = fopen ($url, 'rb');
    if ($file) {
        $newf = fopen ($newfname, 'wb');
        if ($newf) {
            while(!feof($file)) {
                fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
            }
        }
    }
    if ($file) {
        fclose($file);
    }
    if ($newf) {
        fclose($newf);
    }
}
129
xaav

Essayez d'utiliser cURL

set_time_limit(0); // unlimited max execution time
$options = array(
  CURLOPT_FILE    => '/path/to/download/the/file/to.Zip',
  CURLOPT_TIMEOUT =>  28800, // set this to 8 hours so we dont timeout on big files
  CURLOPT_URL     => 'http://remoteserver.com/path/to/big/file.Zip',
);

$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);

Je ne suis pas sûr, mais je crois qu'avec l'option CURLOPT_FILE, il écrit pendant l'extraction des données, c.-à-d. non tamponné.

63
prodigitalson

Ci-dessus, il y a un exemple (cité par prodigitalson) de code qui ne fonctionne pas (raison: fopen manquant dans CURLOPT_FILE - http://www.webdeveloper.com/forum/showthread.php?268299-RESOLVED-PHP-script- pour-un-fichier-de-telechargement-un-pzck-run-autre-script-php ). Je ne peux pas ajouter de commentaire car mon nombre de points est trop faible. Ci-dessous, je donne un exemple de travail (cela fonctionne aussi pour "url locale"):

function downloadUrlToFile($url, $outFileName)
{   
    if(is_file($url)) {
        copy($url, $outFileName); 
    } else {
        $options = array(
          CURLOPT_FILE    => fopen($outFileName, 'w'),
          CURLOPT_TIMEOUT =>  28800, // set this to 8 hours so we dont timeout on big files
          CURLOPT_URL     => $url
        );

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        curl_exec($ch);
        curl_close($ch);
    }
}
20
Kamil Kiełczewski
  1. Créez un dossier appelé "téléchargements" sur le serveur de destination
  2. Enregistrez [ce code] dans le fichier .php et exécutez-le dans le serveur de destination.

Téléchargeur:

<html>
<form method="post">
<input name="url" size="50" />
<input name="submit" type="submit" />
</form>
<?php
    // maximum execution time in seconds
    set_time_limit (24 * 60 * 60);

    if (!isset($_POST['submit'])) die();

    // folder to save downloaded files to. must end with slash
    $destination_folder = 'downloads/';

    $url = $_POST['url'];
    $newfname = $destination_folder . basename($url);

    $file = fopen ($url, "rb");
    if ($file) {
      $newf = fopen ($newfname, "wb");

      if ($newf)
      while(!feof($file)) {
        fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
      }
    }

    if ($file) {
      fclose($file);
    }

    if ($newf) {
      fclose($newf);
    }
?>
</html> 
19
stra8edge
set_time_limit(0); 
$file = file_get_contents('path of your file');
file_put_contents('file.ext', $file);
16
Dimmy

Il y a 3 façons:

  1. contenu_fichier_fichier et contenu_fichier_fichier
  2. CURL
  3. fopen

Vous pouvez trouver des exemples à partir d'ici .

8
Hoan Huynh

Utilisez une méthode simple en php copy()

copy($source_url, $local_path_with_file_name);

Remarque: si le fichier de destination existe déjà, il sera écrasé.

Fonction copy ()

Remarque: vous devez définir l'autorisation 777 pour le dossier de destination. Utilisez cette méthode lorsque vous téléchargez sur votre ordinateur local.

Remarque spéciale: 777 est une autorisation sous Unix avec autorisation complète de lecture/écriture/exécution sur le propriétaire, le groupe et tout le monde. En général, nous accordons cette autorisation. aux actifs qui ne sont pas vraiment nécessaires pour être cachés du public sur un serveur Web. Exemple: dossier images.

Je l'utilise pour télécharger le fichier

function cURLcheckBasicFunctions()
{
  if( !function_exists("curl_init") &&
      !function_exists("curl_setopt") &&
      !function_exists("curl_exec") &&
      !function_exists("curl_close") ) return false;
  else return true;
}

/*
 * Returns string status information.
 * Can be changed to int or bool return types.
 */
function cURLdownload($url, $file)
{
  if( !cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions";
  $ch = curl_init();
  if($ch)
  {

    $fp = fopen($file, "w");
    if($fp)
    {
      if( !curl_setopt($ch, CURLOPT_URL, $url) )
      {
        fclose($fp); // to match fopen()
        curl_close($ch); // to match curl_init()
        return "FAIL: curl_setopt(CURLOPT_URL)";
      }
      if ((!ini_get('open_basedir') && !ini_get('safe_mode')) || $redirects < 1) {
        curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_REFERER, 'http://domain.com/');
        if( !curl_setopt($ch, CURLOPT_HEADER, $curlopt_header)) return "FAIL: curl_setopt(CURLOPT_HEADER)";
        if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirects > 0)) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
        if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
        if( !curl_setopt($ch, CURLOPT_MAXREDIRS, $redirects) ) return "FAIL: curl_setopt(CURLOPT_MAXREDIRS)";

        return curl_exec($ch);
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_REFERER, 'http://domain.com/');
        if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false)) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
        if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
        if( !curl_setopt($ch, CURLOPT_HEADER, true)) return "FAIL: curl_setopt(CURLOPT_HEADER)";
        if( !curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)) return "FAIL: curl_setopt(CURLOPT_RETURNTRANSFER)";
        if( !curl_setopt($ch, CURLOPT_FORBID_REUSE, false)) return "FAIL: curl_setopt(CURLOPT_FORBID_REUSE)";
        curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071204 Ubuntu/7.10 (gutsy) Firefox/2.0.0.11');
    }
      // if( !curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true) ) return "FAIL: curl_setopt(CURLOPT_FOLLOWLOCATION)";
      // if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
      // if( !curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)";
      if( !curl_exec($ch) ) return "FAIL: curl_exec()";
      curl_close($ch);
      fclose($fp);
      return "SUCCESS: $file [$url]";
    }
    else return "FAIL: fopen()";
  }
  else return "FAIL: curl_init()";
}
5
Hoàng Vũ Tgtt

A PHP 4 & 5 Solution:

readfile () ne présentera pas de problème de mémoire, même lors de l'envoi de gros fichiers, par lui-même. Une URL peut être utilisée comme nom de fichier avec cette fonction si les wrappers fopen ont été activés.

http://php.net/manual/en/function.readfile.php

4
Eric Leroy