begin process at 2012 02 09 10:08:41
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Class et Objet ( POO )

 > CLASS D'ENSEMBLE DE FICHIERS À TÉLÉCHARGER

CLASS D'ENSEMBLE DE FICHIERS À TÉLÉCHARGER


 Information sur la source

Note :
Aucune note
Catégorie :Class et Objet ( POO ) Niveau :Initié Date de création :24/02/2005 Date de mise à jour :27/07/2005 15:32:46 Vu :3 734

Auteur : JeanPoldeux

Ecrire un message privé
Commentaire sur cette source (10)
Ajouter un commentaire et/ou une note

 Description

Cette classe permet d'instancier des objets représentant un
ensemble de fichiers qui pourront être téléchargés.
L'utilisation est assez intuitive :
- Instancier un objet
- ajouter des fichiers à l'ensemble par la méthode
                "addFile(nom_du_fichier)"
- supprimer des fichiers par la méthode
                "removeFile(nom_du_fichier)"
- supprimer tous les fichiers par la méthode  
                "removeFiles()"
- démarrer un téléchargement par la méthode
                "startDownload(nom_du_fichier)" ou "startDownloadIndex(index)"

Cette classe peut être utile lorsqu'on a une liste de fichiers dans une base
de données et que l'on récupère les noms de ceux-ci par une fonction SQL
dont le retour est généralement un tableau.

Source

  • <?php
  • /**
  • * Project:
  • * File: fmk_download_inc.php
  • * Class: Download
  • *
  • * This class makes you able to create a downloadable object that
  • * contains a set of downloadable files and start the download of a
  • * specific one.
  • *
  • * @author jean_poldeux <jean_poldeux@hotmail.com>
  • * @date December 20th, 2004
  • * Updated July 26th, 2005
  • * @version 0.1
  • */
  • class Download
  • {
  • /**
  • * Basic constructor that initialises mimeTypes allowed
  • */
  • function Download()
  • {
  • $this->filenames=array();
  • $this->types=array();
  • $this->mime=array(
  • array(".htm","text/html"),
  • array(".html","text/html"),
  • array(".txt","text/plain"),
  • array(".gif","image/gif"),
  • array(".jpg","image/jpeg"),
  • array(".zip","application/zip"),
  • array(".pdf","application/pdf"),
  • array(".ppt","application/mspowerpoint"),
  • array(".xls","application/excel"),
  • array(".doc","application/msword"),
  • array(".exe","application/octet-stream")
  • );
  • }
  • /**
  • * Add a file to the current set
  • * @param $filename : File Name that can be downloaded (STRING)
  • * @return : Boolean value = TRUE if the has correctly been added - FALSE if it isn't a file, the file doesn't exist
  • * or is already in the set
  • */
  • function addFile($filename)
  • {
  • //Check if it is really a file and if it exists on the disk
  • if (is_file($filename) && file_exists($filename))
  • {
  • //Check if the file is not already in
  • if(!in_array($filename,$filenames))
  • {
  • //add it to the file set
  • array_push($this->filenames,$filename);
  • $extension=substr($filename,strrpos($filename,'.')+1);
  • //Check the type of download required and add it to the set
  • for($i=0;$i<=count($this->mime);$i++)
  • {
  • if (strcmp($extension,$this->mime[$i][0])==0)
  • {
  • array_push($this->types,$this->mime[$i][1]);
  • return true;
  • }
  • }
  • return false;
  • }
  • else return false;
  • }
  • else return false;
  • }
  • /**
  • * Remove a specific file from the set given by the index number
  • * @param $index : index value of the file that has to be deleted (INTEGER)
  • * @return : Boolean value = TRUE if it has correctly been removed - FALSE if the index is out of bounds or not number
  • */
  • function removeFile($index)
  • {
  • if(is_int($index) && $index>0 && $index<=count($this->filenames))
  • {
  • array_splice($this->filenames,($index-1),1);
  • array_splice($this->types,($index-1),1);
  • return true;
  • }
  • else return false;
  • }
  • /**
  • * Remove all files from the set
  • */
  • function removeFiles()
  • {
  • array_splice($this->filenames,0);
  • array_splice($this->types,0);
  • }
  • /**
  • * Get the number of files that are contained in the set
  • * @return : Number of files in the set (INTEGER)
  • */
  • function getNbFiles()
  • {
  • return count($this->filenames);
  • }
  • /**
  • * Add a new mime type to the default one
  • * @param $extension : extension of the new file type (STRING)
  • * @param $handling_method : download method which depends on the new file type (STRING)
  • * @return : Boolean value = TRUE if it has correctly insered - FALSE if the extension already exists
  • */
  • function addMimeType($extension, $handling_method)
  • {
  • //Add a dot before file extension if there isn't one
  • if(strcmp(substr($extension, 0, 1),".") != 0)
  • {
  • $extension = ".".$extension;
  • }
  • //Check if the extension doesn't already exists in this object
  • if(array_key_exists($extension, $mime)
  • {
  • return false;
  • }
  • else
  • {
  • $this->mime[$extension] = $handling_method;
  • }
  • }
  • /**
  • * Start the download of specific file given by the index number
  • * @param $index : (INTEGER) index value of the file that has to be downloaded
  • * @return : Boolean value = TRUE if it has correctly started - FALSE if the index is out of bounds or not number
  • */
  • function startDownloadIndex($index)
  • {
  • if(is_int($index) && $index>0 && $index<=count($this->filenames))
  • {
  • $file=basename($this->filenames[$index-1]);
  • header("Content-disposition: attachment; filename=".$this->filenames[$index-1]);
  • header("Content-Type: application/force-download");
  • header("Content-Transfer-Encoding: ".$this->types[$index-1]."\n");
  • header("Content-Length: ".filesize($this->filenames[$index-1]));
  • header("Pragma: no-cache");
  • header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, public");
  • header("Expires: 0");
  • readfile($this->filenames[$index-1]);
  • return true;
  • }
  • else return false;
  • }
  • /**
  • * Start the download of specific file given by the filename
  • * @param $filename : (STRING) Name of the file that has to be downloaded
  • * @return : Boolean value = TRUE if it has correctly started - FALSE if the index is out of bounds or not number
  • */
  • function startDownloadFile($filename)
  • {
  • $index=array_search($this->filenames)
  • if($index)
  • {
  • $file=basename($this->filenames[$index-1]);
  • header("Content-disposition: attachment; filename=".$this->filenames[$index-1]);
  • header("Content-Type: application/force-download");
  • header("Content-Transfer-Encoding: ".$this->types[$index-1]."\n");
  • header("Content-Length: ".filesize($this->filenames[$index-1]));
  • header("Pragma: no-cache");
  • header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, public");
  • header("Expires: 0");
  • readfile($this->filenames[$index-1]);
  • return true;
  • }
  • else return false;
  • }
  • /**
  • * @var Set of files names (STRING INDEXED ARRAY)
  • */
  • var $filenames;
  • /**
  • * @var Set of download method. It depends on the file type (STRING INDEXED ARRAY)
  • */
  • var $types;
  • /**
  • * @var Set of mime types that are allowed (STRING INDEXED ARRAY)
  • */
  • var $mime;
  • }
  • ?>
<?php
/**
 * Project:
 * File:        fmk_download_inc.php
 * Class:       Download
 *
 * This class makes you able to create a downloadable object that
 * contains a set of downloadable files and start the download of a
 * specific one.
 *
 * @author jean_poldeux <jean_poldeux@hotmail.com>
 * @date December 20th, 2004
 * Updated July 26th, 2005
 * @version 0.1
 */

class Download
    {
    /**
     * Basic constructor that initialises mimeTypes allowed
     */
    function Download()
        {
        $this->filenames=array();
        $this->types=array();
        $this->mime=array(
                          array(".htm","text/html"),
                          array(".html","text/html"),
                          array(".txt","text/plain"),
                          array(".gif","image/gif"),
                          array(".jpg","image/jpeg"),
                          array(".zip","application/zip"),
                          array(".pdf","application/pdf"),
                          array(".ppt","application/mspowerpoint"),
                          array(".xls","application/excel"),
                          array(".doc","application/msword"),
                          array(".exe","application/octet-stream")
                          );
        }
        
    /**
     * Add a file to the current set
     * @param $filename : File Name that can be downloaded (STRING)
     * @return : Boolean value = TRUE if the has correctly been added - FALSE if it isn't a file, the file doesn't exist
     * or is already in the set
     */
    function addFile($filename)
        {
        //Check if it is really a file and if it exists on the disk
        if (is_file($filename) && file_exists($filename))
            {
            //Check if the file is not already in
            if(!in_array($filename,$filenames))
                {
                //add it to the file set
                array_push($this->filenames,$filename);
                $extension=substr($filename,strrpos($filename,'.')+1);
                //Check the type of download required and add it to the set
                for($i=0;$i<=count($this->mime);$i++)
                    {
                    if (strcmp($extension,$this->mime[$i][0])==0)
                        {
                        array_push($this->types,$this->mime[$i][1]);
                        return true;
                        }
                    }
                return false;
                }
            else return false;
            }
        else return false;
        }
        
    /**
     * Remove a specific file from the set given by the index number
     * @param $index : index value of the file that has to be deleted (INTEGER)
     * @return : Boolean value = TRUE if it has correctly been removed - FALSE if the index is out of bounds or not number
     */
    function removeFile($index)
        {
        if(is_int($index) && $index>0 && $index<=count($this->filenames))
            {
            array_splice($this->filenames,($index-1),1);
            array_splice($this->types,($index-1),1);
            return true;
            }
        else return false;
        }
        
    /**
     * Remove all files from the set
     */
    function removeFiles()
        {
        array_splice($this->filenames,0);
        array_splice($this->types,0);
        }
        
    /**
     * Get the number of files that are contained in the set
     * @return : Number of files in the set (INTEGER)
     */
    function getNbFiles()
        {
        return count($this->filenames);
        }
        
    /**
     * Add a new mime type to the default one
     * @param $extension : extension of the new file type (STRING)
     * @param $handling_method : download method which depends on the new file type (STRING) 
     * @return : Boolean value = TRUE if it has correctly insered - FALSE if the extension already exists
     */
    function addMimeType($extension, $handling_method)
        {
        //Add a dot before file extension if there isn't one
        if(strcmp(substr($extension, 0, 1),".") != 0)
          {
          $extension = ".".$extension;
          }
        //Check if the extension doesn't already exists in this object
        if(array_key_exists($extension, $mime)
          {
          return false;
          }
        else
          {
          $this->mime[$extension] = $handling_method;
          }
        }
        
    /**
     * Start the download of specific file given by the index number
     * @param $index : (INTEGER) index value of the file that has to be downloaded
     * @return : Boolean value = TRUE if it has correctly started - FALSE if the index is out of bounds or not number
     */
    function startDownloadIndex($index)
        {
        if(is_int($index) && $index>0 && $index<=count($this->filenames))
            {
            $file=basename($this->filenames[$index-1]);
            header("Content-disposition: attachment; filename=".$this->filenames[$index-1]);
            header("Content-Type: application/force-download");
            header("Content-Transfer-Encoding: ".$this->types[$index-1]."\n");
            header("Content-Length: ".filesize($this->filenames[$index-1]));
            header("Pragma: no-cache");
            header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, public");
            header("Expires: 0");
            readfile($this->filenames[$index-1]);
            return true;
            }
        else return false;
        }
    /**
     * Start the download of specific file given by the filename
     * @param $filename : (STRING) Name of the file that has to be downloaded
     * @return : Boolean value = TRUE if it has correctly started - FALSE if the index is out of bounds or not number
     */
    function startDownloadFile($filename)
        {
        $index=array_search($this->filenames)
        if($index)
            {
            $file=basename($this->filenames[$index-1]);
            header("Content-disposition: attachment; filename=".$this->filenames[$index-1]);
            header("Content-Type: application/force-download");
            header("Content-Transfer-Encoding: ".$this->types[$index-1]."\n");
            header("Content-Length: ".filesize($this->filenames[$index-1]));
            header("Pragma: no-cache");
            header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, public");
            header("Expires: 0");
            readfile($this->filenames[$index-1]);
            return true;
            }
        else return false;
        }

 /**
  * @var Set of files names (STRING INDEXED ARRAY)
  */
  var $filenames;   
 
 /**
  * @var Set of download method. It depends on the file type (STRING INDEXED ARRAY)
  */
  var $types;

 /**
  * @var Set of mime types that are allowed (STRING INDEXED ARRAY)
  */
  var $mime;
  }

?>




 Historique

24 février 2005 02:04:12 :
24 février 2005 23:21:46 :
Suite à une erreur d'inattention de ma part et le retour au PHP après un long moment de programmation en C++. Corrections : * Suppression du constructeur vierge * Nouveau nom de fonction pour startDownloadInd($index)
24 février 2005 23:27:22 :
25 février 2005 17:31:27 :
25 février 2005 20:31:31 :
27 juillet 2005 15:32:46 :
Nouvelle fonction d'ajout de Mime type qui ne font pas partie intégrante du constructeur

 Sources du même auteur

Source avec Zip CLASS DE FORMULAIRE HTML
Source avec Zip CLASS DE CONNEXION MYSQL
CLASS D'OBJET TEXTE
Source avec Zip CLASS DE TABLEAU HTML

 Sources de la même categorie

CLASSE DE GESTION DE "VARIABLES GLOBALES D'ENVIRONNEMENT" par pifou25
Source avec Zip COLLECTION.CLASS.MIN.PHP par thunderhunter
Source avec Zip SIMPLETEMPLATE par thunderhunter
Source avec Zip Source avec une capture VOIR QUI VISITE VOTRE SITE par Dariumis
Source avec Zip CLASS SIMPLE CBASEDONNEE par smag42

Commentaires et avis

Commentaire de GRenard le 24/02/2005 16:10:10

nah nah... on est pas sur un site de C++... en php on a pas le droit de déclarer 2 fois les fonctions, même si celles-ci ont des arguments différents. (encore moins avec des types différents... php ne fait pas la différence !)
Donc essais ta fonction, elle ne fonctionne pas !
Download() et startDownload() sont en doubles...

Commentaire de JeanPoldeux le 24/02/2005 23:30:56

En effet, cette erreur d'inattention est maintenant corrigée. Après beaucoup de temps de programmation en C++ avec surdéfiniton de focntions, je n'ai plus songé que c'était impossible en PHP puisque les variables peuvent prendre des contenus de différents types en exécution.

Merci pour la remarque

Commentaire de Naixn le 25/02/2005 12:26:49

Mmmmh ... juste une question : où est-ce qu'il serais possible de trouver les autres types de header selon les extensions ?
Genre pour une fichier avi, c'est quoi ?
video/avi ?

Commentaire de kiki2sirom le 25/02/2005 14:17:28

Tu peux trouver ça ici

http://webmaster.iu.edu/mimetypes/

@+

Commentaire de Naixn le 25/02/2005 14:22:37

Merci beaucoup, c'est exactement ce que je cherchais :)

Commentaire de Naixn le 25/02/2005 15:19:11

Tiens, JeanPoldeux, je viens de me rendre compte d'un truc qui me chiffonais :  à l'endroit où tu définis les Mime Types, avec un switch, tu ne mets aucun BREAK à la fin de chaque CASE.
J'ai donc regardé la doc PHP, et j'ai vu que le switch analyse chaque cas un par un, mais n'éxécute rien tant qu'aucun cas n'est pas vérifié. Par contre, dès qu'un cas est vérifié, il continue d'éxécuter toutes les insctructions jusqu'à la fin du bloc switch ...
Et donc là, en ayant remplacé tous tes
> array_push($this->types,"xxx");
par des
> echo 'xxx, ';
Et en prenant la variable
> $ext = 'zip';
J'obtiens :
> application/zip, application/pdf, image/gif, image/jpeg, text/html, text/html, text/plain,

Et j'imagine que ce n'est pas du tout le cas voulu.

J'imagine donc qu'il va te falloir mettre des
> break;
à la fin de chaque conditions.

> case "zip":
>      array_push($this->types,"application/zip");
>      break;
> case "pdf":
>      array_push($this->types,"application/pdf");
>      break;

etc.

Sinon, une question, pourquoi les fichiers HTML et TXT retournent TRUE et pas les autres ? Et où sert ce TRUE ?
J'ai pas trop réussi à comprendre.

Commentaire de JeanPoldeux le 25/02/2005 17:42:08

En effet, une condition switch est analysée au cas par cas jusqu'à ce qu'elle soit vérifiée et l'exécution poursuit sur toutes les instructions suivantes. Cependant, le mot clé return permettant de fixer la valeur de retour a comme conséquence que l'exécution quitte immédiatement le corps d'une fonction après l'exécution de l'instruction return.

L'omission du break était donc tout à fait volontaire puisqu'inutile mais les instructions return true sous chaque condition switch ne l'était pas. Le but de ce return true ou return flase permet que la fonction renvoit vrai si le Mimetype est existe et que le fichier peut donc être téléchargé. Elle renvoit faux dans tous les autres cas(default: ).

Commentaire de Naixn le 25/02/2005 19:14:01

D'accord. Je comprends mieux.
Donc l'intérêt d'avoir mis des
> return TRUE;
c'est pour, j'imagine, pouvoir faire ça :

> $file = 'fichier.nawak';
> $dl = new Download;
> if(!$dl->addFile($file))
>       echo 'Le fichier ' . $file . ' n\'a put être ajouté.';

Je me trompe ?

Parcequ'il est vrai qu'avec seulement
> break;
on ne peut pas faire ça.

Sinon, ne devrais tu pas soit compléter la liste, soit mettre un style de 'application/force-download' ? Pas forcément celui là, parceque bon, mine de rien, c'est bien peu sûr de mettre ça ( force download ), mais là, bien que la source soit sympa, elle n'est pas complète de par sa gestion mineure des fichiers ( je veux dire par là qu'elle ne gère pas un grand nombre d'extensions ).

PS : HTML est en double :)

Commentaire de JeanPoldeux le 25/02/2005 20:23:52

Pour la valeur de retour, c'est exactement ce principe là.

Il est vrai que la gestion des extensions est limitée mais elle suffit amplement à l'utilisation que j'en fais. De plus, de par son architecture, chaque progammeur peut assez simplement ajouter à cette classe les Mimetypes qui lui sont nécessaires en fonction du projet.
Une autre solution serait de définir un tableau de constantes à deux indices reprenant les extensions et les mimeTypes et de remplacer le switch par une boucle de ce type:

// $mime[][0] : comprend les extensions (.htm, .txt, .html, ...)
// $mime[][1] : comprend les types (application/pdf)

for($i=0;$i<=count($mime);$i++) {
  if ($extension==$mime[$i][0]) {
       array_push($this->types,$mime[$i][1]);
        return true;
      }
  }
return false;

Il suffirait alors d'initialiaser la variable $mime dans le constructeur

$mime=array(array(".zip","application/zip"),array(".pdf","application/pdf"));

avec tous les types qui pourront être télécharger.

Commentaire de JeanPoldeux le 25/02/2005 20:40:06

Comme il s'agit de chaine de caractères, la condition dans la boucle devrait être
if (strcmp($extension,$mime[$i][0])==0)

SORRY

 Ajouter un commentaire




Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Février 2012
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
272829    

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,811 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales