Notice: Undefined index: GEOIP_CITY in /var/www/vhosts/geekinside.fr/httpdocs/overall.php on line 7

Notice: Undefined index: GEOIP_REGION_NAME in /var/www/vhosts/geekinside.fr/httpdocs/overall.php on line 7
Geekin'Side
Français
English

Classe d'upload de fichiers en PHP

Par Admin, mer 05 jan 2011 20:18:44 - Catégorie : Développement

Commentaires 0 Commentaires

N'ayant pas trouvé de classe simple et gérant correctement les exceptions pour uploader des fichiers sur un serveur via PHP, j'ai décidé de développer ma propre classe.

Voici donc sa première version, qui, tout en restant simple, permet déjà tout ce qui a pu m'être nécessaire, à savoir :

  • Définir les types de fichiers autorisés (via leur MIME-type ou leur extension).
  • Laisser la classe catcher les exceptions elle-même ou les catcher soi-même pour pouvoir les gérer à sa façon.
  • Activer un mode debug. Il est possible de l'activer en mode HTML, ou bien directement via console.debug() en Javascript.
  • Définir la taille maximale des fichiers pouvant être uploadés. 
  • Définir s'il faut ou non écraser les fichiers qui sont déjà présents sur le serveur (nom identique). 
  • Définir les noms des fichiers pour qu'ils soient envoyés avec le nom que vous souhaitez. (à partir du script en version 1.0.1)

Ce script est décomposé en 2 classes distinctes :

1. La classe à proprement parler. Elle gère l'intégralité des fonctionnalités. C'est elle qui est instanciée.

PHP : class_Uploader.phpAfficher/Masquer le code
<?php
/*
    Version : 1.0.1
    Last modified : 08/01/2011
    Author : Thomas Bordinat
    Email : ulti@geekinside.fr
    Website : http://www.geekinside.fr

    This program is free software. It comes without any warranty, to
    the extent permitted by applicable law. You can redistribute it
    and/or modify it under the terms of the Do What The Fuck You Want
    To Public License, Version 2, as published by Sam Hocevar. See
    http://sam.zoy.org/wtfpl/COPYING for more details.
*/
namespace GeekinSide;

define('UPLOAD_UNIT_OCTET'1);
define('UPLOAD_UNIT_KO'2);
define('UPLOAD_UNIT_MO'3);
define('UPLOAD_UNIT_GO'4);

/**
 * SimpleUploader allow you to upload files easily.
 *    Just build your HTML form, and after submit, use the uploader object to save files on your server.
 *
 * Example :
 *
 * [code]
 *        $uploader = new GeekinSide\Uploader();
 *        $uploader->setDestinationFolder('./uploadDir/');
 *
 *        $uploader->setOverwrite(true);
 *
 *        if($uploader->upload()) {
 *            echo '<pre>'; var_dump($uploader->getUploadInformation()); echo '</pre>';
 *        }
 * [/code]
 *
 *
 * See full documentation and get updates at www.geekinside.fr
 *
 *
 * @author Thomas Bordinat <ulti@geekinside.fr>
 * @since PHP 5.3.0
 */
class Uploader {

    
/**
     * array(<String>) Allowed MIME
     * default : everything is allowed, this is inadvisable
     */
    
private $_allowedMime = array();

    
/**
     *    boolean Should this class catch Exception ? If not, you'll have to the way you want.
     *    default value : true
     */
    
private $_catchException true;

    
/**
     *    String/boolean If false, debug is desactivated. Else :
     *        - 'js'             =        Debug in JS console
     *        - 'html'         =        Debug in HTML
     *    default value : false
     */
    
private $_debug false;

    
/**
     *    String Path of the folder where files will be uploaded (with or without the final /)
     */
    
private $_destinationFolder '.';

    
/**
     *    array() Contains all $_FILES[]
     */
    
private $_files;

    
/**
     *    int Available space on hard drive (octet)
     */
    
private $_freeSpace;

    
/**
     * int Max file size (octet)
     * default : 0 = no limit
     */
    
private $_maxFileSize 0;
    
    
/**
     * array(String) Name(s) to give to uploaded files
     */
    
private $_names '';

    
/**
     *    boolean Should the Uploader overwrite files in the destination folder during upload if a file with the same name exists ?
     *    default value : false
     */
    
private $_overwrite false;

    
/**
     *    boolean This boolean is true when uploads are done
     */
    
private $_uploadOk false;

    
/**
     *    array() Contains all uploads information
     */
    
private $_uploadInformation = array();

    
/**
     *    Constructs an uploader instance
     *
     * @param debug (@see $_debug)
     */
    
public function __construct($debug=false) {
        require_once(
dirname(__FILE__).'/class_UploaderException.php');
        
$this->setDebug($debug);
        
$this->debug('__construct()');
        
$this->initFiles();
    }

    
/**
     *    Performs the upload
     *
     * @return true if all is ok
     * @throws UploaderException
     */
    
public function upload() {
        
$this->debug('upload()');

        try {
            
$this->checkDestination();
            
$this->initFreeSpace();

            
// Number of uploaded files
            
$i 0;
            
            
$names $this->getNames();

            foreach(
$this->getFiles() as $form) {

                foreach(
$form as $file) {
                    
$this->debug('-> File in progress... '.print_r($filetrue));
                    if(
$file['size']>0) {
                        if(
$file['error']!=UPLOAD_ERR_OK) {
                            throw new 
UploaderException($file['error']);
                        }

                        if(!
$this->checkMime($file['type'])) {
                            
$this->debug('--> File mime not allowed');
                            
// If the mime is not allowed, we store the information into the $_uploadInformation array
                            
$this->_uploadInformation[] = array(
                                
'index' => $file['index'],
                                
'uploaded' => false,
                                
'name' => $file['name'],
                                
'type' => $file['type'],
                                
'typeAllowed' => false,
                                
'size' => $file['size'],
                                
'sizeOk' => true,
                                
'path' => null,
                                
'overwrite' => false
                            
);
                        }
                        elseif(!
$this->checkFileSize($file['size'])) {
                            
$this->debug('--> File is too big');
                            
// If the file is too big, we store the information into the $_uploadInformation array
                            
$this->_uploadInformation[] = array(
                                
'index' => $file['index'],
                                
'uploaded' => false,
                                
'name' => $file['name'],
                                
'type' => $file['type'],
                                
'typeAllowed' => true,
                                
'size' => $file['size'],
                                
'sizeOk' => false,
                                
'path' => null,
                                
'overwrite' => false
                            
);
                        }
                        else {
                            
$fileAlreadyExists file_exists($this->getDestinationFolder().$file['name']);

                            
// If we can't overwrite the file, we store the information into the $_uploadInformation array
                            
if(!$this->getOverwrite() && $fileAlreadyExists) {
                                
$this->debug('--> File already exists, do not overwrite');
                                
$this->_uploadInformation[] = array(
                                    
'index' => $file['index'],
                                    
'uploaded' => false,
                                    
'name' => $file['name'],
                                    
'type' => $file['type'],
                                    
'typeAllowed' => true,
                                    
'size' => $file['size'],
                                    
'sizeOk' => true,
                                    
'path' => null,
                                    
'overwrite' => false
                                
);
                            }
                            else {
                                if(isSet(
$names[$file['index']]) && !empty($names[$file['index']])) {
                                    
$this->debug('--> Replacing '.$file['name'].' by '.$names[$file['index']]);
                                    
$file['name'] = $names[$file['index']];
                                }
                                
                                
// Upload done, the file has been moved to his destination
                                
if(@move_uploaded_file($file['tmp_name'], $this->getDestinationFolder().$file['name'])) {
                                    
$this->debug('--> File moved successfully from tmp to his final destination');
                                    
$this->_uploadInformation[] = array(
                                        
'index' => $file['index'],
                                        
'uploaded' => true,
                                        
'name' => $file['name'],
                                        
'type' => $file['type'],
                                        
'typeAllowed' => true,
                                        
'size' => $file['size'],
                                        
'sizeOk' => true,
                                        
'path' => $this->getDestinationFolder().$file['name'],
                                        
'overwrite' => $fileAlreadyExists true false
                                    
);
                                }
                                
// An error occurred with the move_uploaded_file function, we try to find the problem
                                
else {
                                    
$this->debug('--> Error with move_uploaded_file function');
                                    
// We check the space available...
                                    
if($file['size']>$this->getFreeSpace()) {
                                        throw new 
UploaderException(UPLOAD_ERR_MOVE_UPLOADED_FILE_FREE_SPACE);
                                    }
                                    
// WTF happened ?!
                                    
else {
                                        throw new 
UploaderException(UPLOAD_ERR_MOVE_UPLOADED_FILE);
                                    }
                                }
                            }
                        }

                        
$this->setFreeSpace($this->getFreeSpace()-$file['size']);
                        ++
$i;
                    }
                }
            }

            if(
$i==0) {
                throw new 
UploaderException(UPLOAD_ERR_NO_FILE);
            }

            
$this->setUploadOk(true);
            return 
true;
        }
        catch (\
Exception $e) {
            if(
$this->_catchException) {
                if(
$this->_debug!==false) {
                    
$this->debug('Exception : '.$e->getMessage());
                }
                else {
                    echo 
'<b>Exception : '.$e->getMessage().'</b>';
                }
            }
            else {
                throw new \
Exception($e->getMessage(), $e->getCode(), $e);
            }

        }
    }


    
/**********
     *
     *
     *     Check
     *
     *
     **********/

    /**
     * Check if all is ok with the destination folder.
     * Add a slash at the end of the destination folder string if there's not
     * @throws UploaderException
     */
    
private function checkDestination() {
        
$this->debug('checkDestination()');
        if(!
is_dir($this->getDestinationFolder())) {
            throw new 
UploaderException(UPLOAD_ERR_DESTINATION_IS_NOT_A_FOLDER);
        }

        if(!
preg_match('#/$#'$this->getDestinationFolder())) {
            
$this->debug('-> add slash');
            
$this->setDestinationFolder($this->getDestinationFolder().'/');
        }

        if(!
is_writable($this->getDestinationFolder())) {
            throw new 
UploaderException(UPLOAD_ERR_CANT_WRITE_DESTINATION_FOLDER);
        }
    }
    
/**
     * Check if the given MIME is allowed
     *
     * @param String MIME
     * @return boolean Does the MIME is allowed ?
     */
    
private function checkMime($mime=null) {
        
$this->debug('checkMime('.$mime.')');
        if(empty(
$mime)) {
            return 
false;
        }
        elseif(
$this->getAllowedMime()!=array()) {
            
$this->debug(print_r($this->getAllowedMime(), true));
            return 
in_array($mime$this->getAllowedMime());
        }
        else {
            return 
true;
        }
    }
    
/**
     * Check if the file is small enough
     * @param int $fileSize
     * @return boolean Does the file size ok ?
     */
    
private function checkFileSize($fileSize) {
        return 
$this->getMaxFileSize()==|| $fileSize<=$this->getMaxFileSize();
    }


    
/**********
     *
     *
     *     Init
     *
     *
     **********/

    /**
     * Get data from $_FILES and build the $_files array with it
     */
    
private function initFiles() {
        
$files = array();
        
        
// File index
        
$j 0;
        foreach(
$_FILES as $formName=>$data) {

            
// Example : <input type="file" name="array[]" />
            
if(is_array($_FILES[$formName]['name'])) {
                
$nbFiles count($_FILES[$formName]['name']);
                for(
$i=0$i<$nbFiles$i++) {
                    foreach(
$_FILES[$formName] as $key=>$value) {
                        
$files[$formName][$i][$key] = $value[$i];
                    }
                    
$files[$formName][$i]['index'] = $j;
                    ++
$j;
                }
            }

            
// Example : <input type="file" name="simpleName" />
            
else {
                foreach(
$_FILES[$formName] as $key=>$value) {
                    
$files[$formName][0][$key] = $value;
                }
                
$files[$formName][0]['index'] = $j;
                ++
$j;
            }

        }

        
/**
         * Fill type if not defined (example: .php file)
         */
        
foreach($files as $keyFiles=>$valueFiles) {
            
$i 0;
            foreach(
$valueFiles as $file) {
                if(empty(
$file['type']) && !empty($file['name'])) {
                    
$this->debug('Fill type for file '.$file['name']);
                    
$mime $this->getMimeForExtension($this->getExtension($file['name']));
                    
$files[$keyFiles][$i]['type'] = $mime[0];
                }
                ++
$i;
            }
        }

        
$this->debug('initFiles() -> '.print_r($filestrue).'');
        
$this->_files $files;
    }
    
/**
     * Get free space on the destination folder
     */
    
private function initFreeSpace() {
        
$this->debug('initFreeSpace()');
        
$this->setFreeSpace(disk_free_space($this->getDestinationFolder()));
    }


    
/**********
     *
     *
     *     Getter
     *
     *
     **********/

    /**
     * Get the allowed mime array
     * @return array(String) $_allowedMime
     */
    
private function getAllowedMime() {
        
$this->debug('getAllowedMime()');
        return 
$this->_allowedMime;
    }
    
/**
     * Get the destination folder
     * @return String $_destinationFolder
     */
    
private function getDestinationFolder() {
        
$this->debug('getDestinationFolder()');
        return 
$this->_destinationFolder;
    }
    
/**
     * Get given file's extension
     * @param String filename
     * @return String extension
     */
    
private function getExtension($fileName) {
        
$pathInfo pathinfo($fileName);
        return 
$pathInfo['extension'];
    }
    
/**
     * Returns the $_files to upload
     * @return array() $_files
     */
    
private function getFiles() {
        
$this->debug('getFiles()');
        return 
$this->_files;
    }
    
/**
     * Get the available space on destination folder
     * @return int $_freeSpace
     */
    
private function getFreeSpace() {
        
$this->debug('getFreeSpace()');
        return 
$this->_freeSpace;
    }
    
/**
     * Get the maximum file size
     * @return int $_maxFileSize
     */
    
private function getMaxFileSize() {
        
$this->debug('getMaxFileSize()');
        return 
$this->_maxFileSize;
    }
    
/**
     * Get the name(s) to give
     * @return array(String) $_names
     */
    
private function getNames() {
        
$this->debug('getNames()');
        return 
$this->_names;
    }
    
/**
     * Get the overwrite property
     * @return boolean $_overwrite
     */
    
public function getOverwrite() {
        
$this->debug('getOverwrite()');
        return 
$this->_overwrite;
    }
    
/**
     * If the upload is done, this method returns some information about the files uploaded
     *
     * @return array(mixed)
     * @example :
     *
     * array( 0=>array(
     *        'uploaded' => true,
     *        'name' => 'filename.jpg',
     *        'type' => 'image/jpg',
     *        'typeAllowed' => true,
     *        'size' => 1573215,
     *        'sizeOk' => true,
     *        'path' => './upload/filename.jpg',
     *        'overwrite' => false
     * ));
     *
     * @throws UploaderException
     */
    
public function getUploadInformation() {
        
$this->debug('getUploadInformation()');
        if(
$this->getUploadOk()) {
            return 
$this->_uploadInformation;
        }
        else {
            throw new 
UploaderException(UPLOAD_ERR_CANT_ACCESS_INFORMATION);
        }
    }
    
/**
     * Get $_uploadOk boolean
     * @return boolean $_uploadOk
     */
    
private function getUploadOk() {
        
$this->debug('getUploadOk()');
        return 
$this->_uploadOk;
    }


    
/**********
     *
     *
     *     Setter
     *
     *
     **********/

    /**
     * Set the allowedMime array
     * @param array(String) $allowedMime
     */
    
public function setAllowedMime($allowedMime) {
        
$this->debug('setAllowedMime('.print_r($allowedMimetrue).')');
        
$this->_allowedMime $allowedMime;
    }
    
/**
     * Set the catchException property
     * @param boolean $catchException
     */
    
public function setCatchException($catchException) {
        
$this->debug('setCatchException('.($catchException 'true' 'false').')');
        
$this->_catchException $catchException;
    }
    
/**
     * Set the destination folder
     * @param String $destinationFolder
     */
    
public function setDestinationFolder($destinationFolder) {
        
$this->debug('setDestinationFolder('.$destinationFolder.')');
        
$this->_destinationFolder $destinationFolder;
    }
    
/**
     * Set the debug property
     * @param boolean $debug
     */
    
public function setDebug($debug) {
        
$this->debug('setDebug('.($debug 'true' 'false').')');
        
$this->_debug $debug;
    }
    
/**
     * Set the available space on destination folder
     * @param int $freeSpace
     */
    
private function setFreeSpace($freeSpace) {
        
$this->debug('setFreeSpace('.$freeSpace.')');
        
$this->_freeSpace $freeSpace;
    }
    
/**
     * Set the max file size property
     * @param int $maxFileSize
     */
    
public function setMaxFileSize($maxFileSize=0$unit=UPLOAD_UNIT_OCTET) {
        switch(
$unit) {
            case 
UPLOAD_UNIT_KO :
                
$maxFileSize *= 1024;
            break;
            case 
UPLOAD_UNIT_MO :
                
$maxFileSize *= 1048576;
            break;
            case 
UPLOAD_UNIT_GO :
                
$maxFileSize *= 1073741824;
            break;
        }
        
$this->debug('setMaxFileSize('.$maxFileSize.')');
        
$this->_maxFileSize $maxFileSize;
    }
    
/**
     * Set the names
     * @param mixed $names
     */
    
public function setNames($names) {
        
$this->debug('setNames('.print_r($namestrue).')');
        if(!
is_array($names)) {
            
$this->_names = array($names);
        }
        else {
            
$this->_names $names;
        }
    }
    
/**
     * Set the overwrite property
     * @param boolean $overwrite
     */
    
public function setOverwrite($overwrite) {
        
$this->debug('setOverwrite('.($overwrite 'true' 'false').')');
        
$this->_overwrite $overwrite;
    }
    
/**
     * Set the uploadOk boolean
     * @param boolean $uploadOk
     */
    
private function setUploadOk($uploadOk) {
        
$this->debug('setUploadOk('.($uploadOk 'true' 'false').')');
        
$this->_uploadOk $uploadOk;
    }


    
/**********
     *
     *
     *     Utilities
     *
     *
     **********/

    /**
     * Add a mime on the $_allowedMime array
     *
     * @param array(String) | String $mime Mime to allow
     */
    
public function addMime($mime) {
        
$this->debug('addMime('.print_r($mimetrue).')');
        if(!
is_array($mime)) {
            
$mime = array($mime);
        }

        
$allowedMime $this->getAllowedMime();
        foreach(
$mime as $toBeAdded) {
            
array_push($allowedMime$toBeAdded);
        }
        
$this->setAllowedMime($allowedMime);
    }
    public function 
addExtension($extension) {
        
$this->debug('addExtention('.$extension.')');
        
$mime $this->getMimeForExtension($extension);
        
$this->addMime($mime);
    }
    
/**
     * Remove a mime off the $_allowedMime array
     *
     * @param array(String) | String $mime Mime to remove
     */
    
public function removeMime($mime) {
        
$this->debug('removeMime('.print_r($mimetrue).')');
        if(!
is_array($mime)) {
            
$mime = array($mime);
        }

        
$allowedMime $this->getAllowedMime();
        
$tmpArray = array();
        foreach(
$allowedMime as $value) {
            if(!
in_array($value$mime)) {
                
array_push($tmpArray$value);
            }
        }
        
$this->setAllowedMime($tmpArray);
    }
    public function 
removeExtension($extension) {
        
$this->debug('removeExtension('.$extension.')');
        
$mime $this->getMimeForExtension($extension);
        
$this->removeMime($mime);
    }
    
/**
     * Get all MIME that corresponds to the given extension
     *
     * @param String $extension Extension needed
     * @return array(String) Mime
     */
    
private function getMimeForExtension($extension) {
        
$this->debug('getMimeForExtension('.$extension.')');
        if(
preg_match('#^\.#'$extension)) {
            
$extension preg_replace('#^\.#'''$extension);
        }

        switch(
$extension) {
            case 
'gif' :
                
$mime = array('image/gif');
            break;
            case 
'jpg' :
            case 
'jpeg' :
            case 
'jpe' :
                
$mime = array('image/jpg''image/jpeg''image/pjpeg');
            break;
            case 
'png' :
                
$mime = array('image/png''image/x-png');
            break;
            case 
'bmp' :
                
$mime = array('image/bmp''image/x-ms-bmp''image/x-windows-bmp');
            break;
            case 
'tiff' :
                
$mime = array('image/tiff');
            break;
            case 
'flv' :
                
$mime = array('video/x-flv');
            break;
            case 
'js' :
                
$mime = array('application/x-javascript');
            break;
            case 
'json' :
                
$mime = array('application/json');
            break;
            case 
'css' :
                
$mime = array('text/css');
            break;
            case 
'xml' :
                
$mime = array('application/xml');
            break;
            case 
'doc' :
            case 
'docx' :
                
$mime = array('application/msword');
            break;
            case 
'xls' :
            case 
'xlt' :
            case 
'xlm' :
            case 
'xld' :
            case 
'xla' :
            case 
'xlc' :
            case 
'xlw' :
            case 
'xll' :
                
$mime = array('application/vnd.ms-excel');
            break;
            case 
'ppt' :
            case 
'pps' :
                
$mime = array('application/vnd.ms-powerpoint');
            break;
            case 
'rtf' :
                
$mime = array('application/rtf');
            break;
            case 
'pdf' :
                
$mime = array('application/pdf');
            break;
            case 
'html' :
            case 
'htm' :
            case 
'php' :
                
$mime = array('text/html');
            break;
            case 
'txt' :
                
$mime = array('text/plain');
            break;
            case 
'mpeg' :
            case 
'mpg' :
            case 
'mpe' :
                
$mime = array('video/mpeg');
            break;
            case 
'mp3' :
                
$mime = array('audio/mpeg3');
            break;
            case 
'wav' :
                
$mime = array('audio/wav');
            break;
            case 
'aiff' :
            case 
'aif' :
                
$mime = array('audio/aiff');
            break;
            case 
'avi' :
                
$mime = array('video/msvideo');
            break;
            case 
'wmv' :
                
$mime = array('video/x-ms-wmv');
            break;
            case 
'mov' :
                
$mime = array('video/quicktime');
            break;
            case 
'zip' :
                
$mime = array('application/zip');
            break;
            case 
'tar' :
                
$mime = array('application/x-tar');
            break;
            case 
'swf' :
                
$mime = array('application/x-shockwave-flash');
            break;
            case 
'odt' :
                
$mime = array('application/vnd.oasis.opendocument.text');
            break;
            case 
'ott' :
                
$mime = array('application/vnd.oasis.opendocument.text-template');
            break;
            case 
'oth' :
                
$mime = array('application/vnd.oasis.opendocument.text-web');
            break;
            case 
'odm' :
                
$mime = array('application/vnd.oasis.opendocument.text-master');
            break;
            case 
'odg' :
                
$mime = array('application/vnd.oasis.opendocument.graphics');
            break;
            case 
'otg' :
                
$mime = array('application/vnd.oasis.opendocument.graphics-template');
            break;
            case 
'odp' :
                
$mime = array('application/vnd.oasis.opendocument.presentation');
            break;
            case 
'otp' :
                
$mime = array('application/vnd.oasis.opendocument.presentation-template');
            break;
            case 
'ods' :
                
$mime = array('application/vnd.oasis.opendocument.spreadsheet');
            break;
            case 
'ots' :
                
$mime = array('application/vnd.oasis.opendocument.spreadsheet-template');
            break;
            case 
'odc' :
                
$mime = array('application/vnd.oasis.opendocument.chart');
            break;
            case 
'odf' :
                
$mime = array('application/vnd.oasis.opendocument.formula');
            break;
            case 
'odb ':
                
$mime = array('application/vnd.oasis.opendocument.database');
            break;
            case 
'odi' :
                
$mime = array('application/vnd.oasis.opendocument.image');
            break;
            case 
'oxt' :
                
$mime = array('application/vnd.openofficeorg.extension');
            break;
            case 
'docm' :
                
$mime = array('application/vnd.ms-word.document.macroEnabled.12');
            break;
            case 
'dotx' :
                
$mime = array('application/vnd.openxmlformats-officedocument.wordprocessingml.template');
            break;
            case 
'dotm' :
                
$mime = array('application/vnd.ms-word.template.macroEnabled.12');
            break;
            case 
'xlsx' :
                
$mime = array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            break;
            case 
'xlsm' :
                
$mime = array('application/vnd.ms-excel.sheet.macroEnabled.12');
            break;
            case 
'xltx' :
                
$mime = array('application/vnd.openxmlformats-officedocument.spreadsheetml.template');
            break;
            case 
'xltm' :
                
$mime = array('application/vnd.ms-excel.template.macroEnabled.12');
            break;
            case 
'xlsb' :
                
$mime = array('application/vnd.ms-excel.sheet.binary.macroEnabled.12');
            break;
            case 
'xlam' :
                
$mime = array('application/vnd.ms-excel.addin.macroEnabled.12');
            break;
            case 
'pptx' :
                
$mime = array('application/vnd.openxmlformats-officedocument.presentationml.presentation');
            break;
            case 
'pptm' :
                
$mime = array('application/vnd.ms-powerpoint.presentation.macroEnabled.12');
            break;
            case 
'ppsx' :
                
$mime = array('application/vnd.openxmlformats-officedocument.presentationml.slideshow');
            break;
            case 
'ppsm' :
                
$mime = array('application/vnd.ms-powerpoint.slideshow.macroEnabled.12');
            break;
            case 
'potx' :
                
$mime = array('application/vnd.openxmlformats-officedocument.presentationml.template');
            break;
            case 
'potm' :
                
$mime = array('application/vnd.ms-powerpoint.template.macroEnabled.12');
            break;
            case 
'ppam' :
                
$mime = array('application/vnd.ms-powerpoint.addin.macroEnabled.12');
            break;
            case 
'sldx' :
                
$mime = array('application/vnd.openxmlformats-officedocument.presentationml.slide');
            break;
            case 
'sldm' :
                
$mime = array('application/vnd.ms-powerpoint.slide.macroEnabled.12');
            break;
            case 
'thmx' :
                
$mime = array('application/vnd.ms-officetheme');
            break;
            case 
'onetoc' :
            case 
'onetoc2' :
            case 
'onetmp' :
            case 
'onepkg' :
                
$mime = array('application/onenote');
            break;
            default :
                
$mime = array('text/plain');
            break;
        }
        return 
$mime;
    }


    
/**********
     *
     *
     *     Debug
     *
     *
     **********/

    /**
     * Display the String $s if the debug property is set to 'js' or 'html'
     * @param String $s String to display
     */
    
private function debug($s) {
        if(
$this->_debug!==false) {
            if(
$this->_debug=='js') {
                echo 
'<script type="text/javascript">console.debug('.json_encode($s).');</script>';
            }
            elseif(
$this->_debug=='html') {
                echo 
'<pre>'.$s.'</pre>';
            }
        }
    }

    
/**
     * Destruct this object
     */
    
public function __destruct() {
        
$this->debug('__destruct()');
    }

}
?>

2. La classe étendant Exception, qui contient toutes les exceptions générées par l'Uploader.

PHP : class_UploaderException.phpAfficher/Masquer le code
<?php
/*
    Author : Thomas Bordinat
    Email : ulti@geekinside.fr
    Website : http://www.geekinside.fr

    This program is free software. It comes without any warranty, to
    the extent permitted by applicable law. You can redistribute it
    and/or modify it under the terms of the Do What The Fuck You Want
    To Public License, Version 2, as published by Sam Hocevar. See
    http://sam.zoy.org/wtfpl/COPYING for more details.
*/
namespace GeekinSide;

/**
 * Adding some new UPLOAD_ERR constants
 */
define('UPLOAD_ERR_DESTINATION_IS_NOT_A_FOLDER'9);
define('UPLOAD_ERR_MOVE_UPLOADED_FILE'10);
define('UPLOAD_ERR_MOVE_UPLOADED_FILE_FREE_SPACE'11);
define('UPLOAD_ERR_CANT_ACCESS_INFORMATION'12);
define('UPLOAD_ERR_CANT_WRITE_DESTINATION_FOLDER'13);

/**
 *
 * Uploader exceptions
 *
 * @author Thomas Bordinat <ulti@geekinside.fr>
 * @since PHP 5.3.0
 */
class UploaderException extends \Exception {
    
/**
     * Constructor
     *
     * @param int $code Error code
     */
    
public function __construct($code) {
        
$message $this->getUploadError($code);
        
parent::__construct($message$code);
    }

    
/**
     * Return the message that you'll find with $e->getMessage(); ($e is an \Exception)
     *
     * @param int $code Error code
     * @return String $message
     */
    
private function getUploadError($code) {
        switch (
$code) {
            case 
UPLOAD_ERR_INI_SIZE :
                
$message 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
            break;
            case 
UPLOAD_ERR_FORM_SIZE :
                
$message 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
            break;
            case 
UPLOAD_ERR_PARTIAL :
                
$message 'The uploaded file was only partially uploaded.';
            break;
            case 
UPLOAD_ERR_NO_FILE :
                
$message 'No file was uploaded.';
            break;
            case 
UPLOAD_ERR_NO_TMP_DIR :
                
$message 'Missing a temporary folder.';
            break;
            case 
UPLOAD_ERR_CANT_WRITE :
                
$message 'Failed to write file to disk.';
            break;
            case 
UPLOAD_ERR_EXTENSION :
                
$message 'A PHP extension stopped the file upload.';
            break;
            case 
UPLOAD_ERR_DESTINATION_IS_NOT_A_FOLDER :
                
$message 'The destination path is not a folder or doesn\'t exists.';
            break;
            case 
UPLOAD_ERR_MOVE_UPLOADED_FILE :
                
$message 'The file cannot be move to the destination folder.';
            break;
            case 
UPLOAD_ERR_MOVE_UPLOADED_FILE_FREE_SPACE :
                
$message 'The uploaded file exceeds the available disk space.';
            break;
            case 
UPLOAD_ERR_CANT_ACCESS_INFORMATION :
                
$message 'Cannot access upload information until it is not ended successfully.';
            break;
            case 
UPLOAD_ERR_CANT_WRITE_DESTINATION_FOLDER :
                
$message 'Failed to write on destination folder.';
            break;
            default :
                
$message 'Unknown error occurred, please contact the author.';
            break;
        }
        return 
$message;
    }

}
?>

Pour illustrer tout ça, rien ne vaut un exemple. Ce fichier est à placer dans le même dossier que les deux classes composant l'Uploader. Il présente un peu son fonctionnement et permet de voir les différentes méthodes utiles.

PHP : uploaderExample.phpAfficher/Masquer le code
<?php
require('./file/php/uploader/class_Uploader.php');

if(!isSet(
$_FILES) || empty($_FILES)) {
    echo 
'<form action="'.$_SERVER['PHP_SELF'].'" method="POST" enctype="multipart/form-data">
        Choose a file to upload : <input name="test" type="file" /><br />
        Choose a file to upload : <input name="array[]" type="file" /><br />
        Choose a file to upload : <input name="array[]" type="file" /><br />
        <input type="submit" value="Upload those files" />
    </form>'
;
}
else {
    try {
        
$uploader = new GeekinSide\Uploader('js');    // Open your JS console to see debug information (or replace 'js' by 'html')
        
$uploader->setDestinationFolder('./log/'); // Files will be uploaded into the current folder

        
$uploader->setOverwrite(true); // If file exists, it will be overwritten

        
$uploader->setMaxFileSize(100UPLOAD_UNIT_KO); // Set the max file size to 10 Ko (you can also use UPLOAD_UNIT_MO, UPLOAD_UNIT_GO or UPLOAD_UNIT_OCTET (by default)

        // Add / Remove available MIME or extensions
        
$uploader->addMime('image/png');
        
$uploader->addMime('image/gif');
        
$uploader->addExtension('zip');
        
$uploader->addMime(array('application/x-javascript''application/json'));
        
$uploader->addMime('text/plain');
        
$uploader->addExtension('.jpg');
        
$uploader->addExtension('.php');
        
$uploader->removeMime('application/json');
        
$uploader->removeExtension('.js');
        
        
$uploader->setNames(array('file1.ext''''file3.ext'));

        
// Upload files
        
if($uploader->upload()) {
            echo 
count($uploader->getUploadInformation()).' file(s) :';

            
$files $uploader->getUploadInformation();
            foreach(
$files as $file) {
                echo 
'<br />';
                foreach(
$file as $key=>$value) {
                    if(
is_bool($value)) {
                        echo 
$key.' : <b>'.($value 'true' 'false').'</b> ';
                    }
                    elseif(
is_null($value)) {
                        echo 
$key.' : <b><i>null</i></b> ';
                    }
                    else {
                        echo 
$key.' : <b>'.$value.'</b> ';
                    }
                }
            }
        }
    }
    catch (
Exception $e) {
        echo 
'Error : '.$e->getMessage();
    }
}
?>

 

Téléchargements Téléchargement Uploader.tar.gz
PHP 5.3.0 minimum
Serveur Linux
Licence WTFPL
En espérant que ça puisse être utile :)

 

Commentaires Commentaires  Laisser un commentaire Laisser un commentaire
Pseudo

DoNotFillIt


Commentaire *



Voir tous les commentaires Voir tous les commentaires

Geekin'Side en 2011

Par Admin, dim 02 jan 2011 22:22:55 - Catégorie : Général

Commentaires 7 Commentaires

Bonjour et bonne année à toutes et à tous :)

Nous profitons de cette incrémentation annale pour présenter un peu ce que nous comptons faire de cette année et faire un petit point sur les 12 mois écoulés.

Notre projet principal, LLDC, avance tranquillement. 2010 lui a apporté une certaine stabilité ainsi que pas mal de nouveautés. Pour 2011, nous prévoyons la sortie de la version 1.0 finale, et le début du développement de nouvelles parties (notamment les héros, mise en place de plusieurs serveurs afin de permettre différentes vitesses et types de jeu..), tout en continuant évidement d'ajouter de petites choses un peu partout, comme à notre habitude ^^

Nous avons pour 2011 d'autres choses en vue, via notre association Geekin'Side (dont nous avons réalisé la version actuelle du site fin 2010).

Ce portail va nous permettre de nous diversifier, et de mettre en place divers projets.

Nous songeons par exemple à un webcron, ou encore à un service permettant de convertir votre crédit téléphonique inutilisé en argent, ainsi qu'un service d'hébergement de forums ou de sites web.

Ces différents services nous permettront de rentabiliser notre serveur, car les finances de l'association sont en déficit (LLDC n'étant pas suffisant pour couvrir les frais).

Nous pensons également à un projet important, dont nous vous reparlerons au moment voulu, relatif au monde des jeux vidéos et plus particulièrement des jeux en ligne ;)

 

Pour bien commencer l'année, nous avons ajouté la possibilité pour vous de partager nos articles sur Facebook et de laisser des commentaires, alors n'hésitez pas ^^ Cela se fait pour le moment de manière anonyme, mais lorsque nous aurons mis en place l'espace membre sur Geekin'Side (lié au compte LLDC, histoire de n'avoir à faire qu'une inscription), cela changera :)

 

Bonne reprise pour ceux qui étaient en vacances ;)

 

L'Équipe Geekin'Side, Harald et Ulti
Commentaires Commentaires  Laisser un commentaire Laisser un commentaire
Pseudo

DoNotFillIt


Commentaire *



Voir tous les commentaires Voir tous les commentaires

Création de Geekin'Side.fr !

Par Admin, dim 12 déc 2010 00:43:59 - Catégorie : Général

Commentaires 0 Commentaires

Début 2008, afin d'officialiser le site www.lldc.fr, nous avons décidé de créer une association régie par la loi du 1er Juillet 1901 et le décret du 16 Août 1901 ayant pour titre "Geekin'Side".

Quel intérêt ? Après LLDC, nous avons envie de mener à bien divers projets. C'est pourquoi nous avons décidé que toutes nos réalisations seraient répertoriées sur un portail. Dans ce cas, pourquoi ne pas en profiter pour se déclarer officiellement, et ainsi avoir le droit de percevoir de l'argent provenant des différentes bannières publicitaires et autres sources de revenus afin de payer les frais d'hébergement et de développement ? Nous verrons jusqu'où cette aventure nous mènera.

Téléchargements

Téléchargement Geekin'Side - Déclaration

Téléchargement Geekin'Side - Statuts

La plateforme Geekin'Side étant désormais en place, nous allons pouvoir nous consacrer à nos projets, tout en continuant le plus possible à développer LLDC.

Commentaires Commentaires  Laisser un commentaire Laisser un commentaire
Pseudo

DoNotFillIt


Commentaire *



Voir tous les commentaires Voir tous les commentaires
Suivez-nous sur Facebook !