bssanchez93

[PHP] - Clase para subida de archivos

May 22nd, 2014
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.52 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Clase que encapsula las funciones de subida de archivos con su
  5.  * seguridad correspondiente
  6.  * @author Brandon Sanchez
  7.  *
  8.  */
  9.  
  10. class FUpload {
  11.  
  12.     private $carpeta = '';
  13.     private $type = array();
  14.     private $maxLength = 0;
  15.     private $extension = array();
  16.     private $mensajes = array('errores' => array(), 'success' => array('cargado' => 0, 'mensaje' => '', 'url' => ''));
  17.    
  18.     /**
  19.      * Inicia la clase asignando la ruta de la carpeta para subir los archivos,
  20.      * si la carpeta no existe la crea, y verifica los permisos de la misma
  21.      *
  22.      * @param string $carpeta -> Ruta relativa a partir del archivo hacia la carpeta donde se subiran los archivos
  23.      */
  24.     function __construct($carpeta) {
  25.         $this->asignarCarpeta($carpeta);
  26.         $this->loadMimeTypes();
  27.         $this->loadMaxSize();
  28.     }
  29.    
  30.     /**
  31.      * Funcion para crear carpeta si no existe
  32.      *
  33.      * @global object $aplicacion
  34.      * @param string $carpeta -> Ruta de la carpeta asignada en el momento de instanciar la clase
  35.      */
  36.     private function asignarCarpeta($carpeta) {
  37.         $carpeta = $carpeta;
  38.        
  39.         if(!is_dir($carpeta)) {
  40.             if(!mkdir($carpeta)) {
  41.                 $this->mensajes['errores'][] = array('codigo' => '003', 'titulo' => 'Error de carpeta', 'mensaje' => 'La carpeta no existe "' . $carpeta . '" y no pudo ser creada.');
  42.             } else {
  43.                 copy($dir_uploads . 'index.html', $carpeta);
  44.                 $this->carpeta = $carpeta;
  45.             }
  46.         } else {
  47.             $this->carpeta = $carpeta;
  48.         }
  49.     }
  50.  
  51.  
  52.     /**
  53.      * Asigna las extensiones permitidas, con ello se asigna directamente el mime/type.
  54.      * Si no se asigna ninguna Extension se da por hecho que todas son permitidas sin
  55.      * restriccion, sin embargo debe ser acorde a su mime/type.
  56.      *
  57.      * @param string or Array $valor -> Contine las extensiones permitidas puede agregar varias en un array de la forma array('ext1', 'ext2', ...)
  58.      */
  59.     public function setExtension($valor) {
  60.         if (is_array($valor)) {
  61.             $this->extension = $valor;
  62.         } else {
  63.             $this->extension[] = $valor;
  64.         }
  65.     }
  66.    
  67.     /**
  68.      * Carga el tamaño maximo de archivo en bytes desde el archivo config.yml
  69.      *
  70.      * @global object $aplicacion
  71.      */
  72.     public function loadMaxSize() {
  73.         $this->maxLength = 15728640; // máximo tamaño en bytes
  74.     }
  75.    
  76.     /**
  77.      * Carga todos los mime/type disponibles en un arra con su respectiva extension
  78.      */
  79.     public function loadMimeTypes() {
  80.         $this->type = array("323" => "text/h323",
  81.             "acx" => "application/internet-property-stream",
  82.             "ai" => "application/postscript",
  83.             "aif" => "audio/x-aiff",
  84.             "aifc" => "audio/x-aiff",
  85.             "aiff" => "audio/x-aiff",
  86.             "asf" => "video/x-ms-asf",
  87.             "asr" => "video/x-ms-asf",
  88.             "asx" => "video/x-ms-asf",
  89.             "au" => "audio/basic",
  90.             "avi" => "video/x-msvideo",
  91.             "axs" => "application/olescript",
  92.             "bas" => "text/plain",
  93.             "bcpio" => "application/x-bcpio",
  94.             "bin" => "application/octet-stream",
  95.             "bmp" => "image/bmp",
  96.             "c" => "text/plain",
  97.             "cat" => "application/vnd.ms-pkiseccat",
  98.             "cdf" => "application/x-cdf",
  99.             "cer" => "application/x-x509-ca-cert",
  100.             "class" => "application/octet-stream",
  101.             "clp" => "application/x-msclip",
  102.             "cmx" => "image/x-cmx",
  103.             "cod" => "image/cis-cod",
  104.             "cpio" => "application/x-cpio",
  105.             "crd" => "application/x-mscardfile",
  106.             "crl" => "application/pkix-crl",
  107.             "crt" => "application/x-x509-ca-cert",
  108.             "csh" => "application/x-csh",
  109.             "css" => "text/css",
  110.             "dcr" => "application/x-director",
  111.             "der" => "application/x-x509-ca-cert",
  112.             "dir" => "application/x-director",
  113.             "dll" => "application/x-msdownload",
  114.             "dms" => "application/octet-stream",
  115.             "doc" => "application/msword",
  116.             "dot" => "application/msword",
  117.             "dvi" => "application/x-dvi",
  118.             "dxr" => "application/x-director",
  119.             "eps" => "application/postscript",
  120.             "etx" => "text/x-setext",
  121.             "evy" => "application/envoy",
  122.             "exe" => "application/octet-stream",
  123.             "fif" => "application/fractals",
  124.             "flr" => "x-world/x-vrml",
  125.             "gif" => "image/gif",
  126.             "gtar" => "application/x-gtar",
  127.             "gz" => "application/x-gzip",
  128.             "h" => "text/plain",
  129.             "hdf" => "application/x-hdf",
  130.             "hlp" => "application/winhlp",
  131.             "hqx" => "application/mac-binhex40",
  132.             "hta" => "application/hta",
  133.             "htc" => "text/x-component",
  134.             "htm" => "text/html",
  135.             "html" => "text/html",
  136.             "htt" => "text/webviewhtml",
  137.             "ico" => "image/x-icon",
  138.             "ief" => "image/ief",
  139.             "iii" => "application/x-iphone",
  140.             "ins" => "application/x-internet-signup",
  141.             "isp" => "application/x-internet-signup",
  142.             "jfif" => "image/pipeg",
  143.             "jpe" => "image/jpeg",
  144.             "jpeg" => "image/jpeg",
  145.             "jpg" => "image/jpeg",
  146.             "js" => "application/x-javascript",
  147.             "latex" => "application/x-latex",
  148.             "lha" => "application/octet-stream",
  149.             "lsf" => "video/x-la-asf",
  150.             "lsx" => "video/x-la-asf",
  151.             "lzh" => "application/octet-stream",
  152.             "m13" => "application/x-msmediaview",
  153.             "m14" => "application/x-msmediaview",
  154.             "m3u" => "audio/x-mpegurl",
  155.             "man" => "application/x-troff-man",
  156.             "mdb" => "application/x-msaccess",
  157.             "me" => "application/x-troff-me",
  158.             "mht" => "message/rfc822",
  159.             "mhtml" => "message/rfc822",
  160.             "mid" => "audio/mid",
  161.             "mny" => "application/x-msmoney",
  162.             "mov" => "video/quicktime",
  163.             "movie" => "video/x-sgi-movie",
  164.             "mp2" => "video/mpeg",
  165.             "mp3" => "audio/mpeg",
  166.             "mpa" => "video/mpeg",
  167.             "mpe" => "video/mpeg",
  168.             "mpeg" => "video/mpeg",
  169.             "mpg" => "video/mpeg",
  170.             "mpp" => "application/vnd.ms-project",
  171.             "mpv2" => "video/mpeg",
  172.             "ms" => "application/x-troff-ms",
  173.             "mvb" => "application/x-msmediaview",
  174.             "nws" => "message/rfc822",
  175.             "oda" => "application/oda",
  176.             "p10" => "application/pkcs10",
  177.             "p12" => "application/x-pkcs12",
  178.             "p7b" => "application/x-pkcs7-certificates",
  179.             "p7c" => "application/x-pkcs7-mime",
  180.             "p7m" => "application/x-pkcs7-mime",
  181.             "p7r" => "application/x-pkcs7-certreqresp",
  182.             "p7s" => "application/x-pkcs7-signature",
  183.             "pbm" => "image/x-portable-bitmap",
  184.             "pdf" => "application/pdf",
  185.             "pfx" => "application/x-pkcs12",
  186.             "pgm" => "image/x-portable-graymap",
  187.             "pko" => "application/ynd.ms-pkipko",
  188.             "pma" => "application/x-perfmon",
  189.             "pmc" => "application/x-perfmon",
  190.             "pml" => "application/x-perfmon",
  191.             "pmr" => "application/x-perfmon",
  192.             "pmw" => "application/x-perfmon",
  193.             "png" => "image/png",
  194.             "pnm" => "image/x-portable-anymap",
  195.             "pot" => "application/vnd.ms-powerpoint",
  196.             "ppm" => "image/x-portable-pixmap",
  197.             "pps" => "application/vnd.ms-powerpoint",
  198.             "ppt" => "application/vnd.ms-powerpoint",
  199.             "prf" => "application/pics-rules",
  200.             "ps" => "application/postscript",
  201.             "pub" => "application/x-mspublisher",
  202.             "qt" => "video/quicktime",
  203.             "ra" => "audio/x-pn-realaudio",
  204.             "ram" => "audio/x-pn-realaudio",
  205.             "ras" => "image/x-cmu-raster",
  206.             "rgb" => "image/x-rgb",
  207.             "rmi" => "audio/mid",
  208.             "roff" => "application/x-troff",
  209.             "rtf" => "application/rtf",
  210.             "rtx" => "text/richtext",
  211.             "scd" => "application/x-msschedule",
  212.             "sct" => "text/scriptlet",
  213.             "setpay" => "application/set-payment-initiation",
  214.             "setreg" => "application/set-registration-initiation",
  215.             "sh" => "application/x-sh",
  216.             "shar" => "application/x-shar",
  217.             "sit" => "application/x-stuffit",
  218.             "snd" => "audio/basic",
  219.             "spc" => "application/x-pkcs7-certificates",
  220.             "spl" => "application/futuresplash",
  221.             "src" => "application/x-wais-source",
  222.             "sst" => "application/vnd.ms-pkicertstore",
  223.             "stl" => "application/vnd.ms-pkistl",
  224.             "stm" => "text/html",
  225.             "svg" => "image/svg+xml",
  226.             "sv4cpio" => "application/x-sv4cpio",
  227.             "sv4crc" => "application/x-sv4crc",
  228.             "t" => "application/x-troff",
  229.             "tar" => "application/x-tar",
  230.             "tcl" => "application/x-tcl",
  231.             "tex" => "application/x-tex",
  232.             "texi" => "application/x-texinfo",
  233.             "texinfo" => "application/x-texinfo",
  234.             "tgz" => "application/x-compressed",
  235.             "tif" => "image/tiff",
  236.             "tiff" => "image/tiff",
  237.             "tr" => "application/x-troff",
  238.             "trm" => "application/x-msterminal",
  239.             "tsv" => "text/tab-separated-values",
  240.             "txt" => "text/plain",
  241.             "uls" => "text/iuls",
  242.             "ustar" => "application/x-ustar",
  243.             "vcf" => "text/x-vcard",
  244.             "vrml" => "x-world/x-vrml",
  245.             "wav" => "audio/x-wav",
  246.             "wcm" => "application/vnd.ms-works",
  247.             "wdb" => "application/vnd.ms-works",
  248.             "wks" => "application/vnd.ms-works",
  249.             "wmf" => "application/x-msmetafile",
  250.             "wps" => "application/vnd.ms-works",
  251.             "wri" => "application/x-mswrite",
  252.             "wrl" => "x-world/x-vrml",
  253.             "wrz" => "x-world/x-vrml",
  254.             "xaf" => "x-world/x-vrml",
  255.             "xbm" => "image/x-xbitmap",
  256.             "xla" => "application/vnd.ms-excel",
  257.             "xlc" => "application/vnd.ms-excel",
  258.             "xlm" => "application/vnd.ms-excel",
  259.             "xls" => "application/vnd.ms-excel",
  260.             "xlt" => "application/vnd.ms-excel",
  261.             "xlw" => "application/vnd.ms-excel",
  262.             "xof" => "x-world/x-vrml",
  263.             "xpm" => "image/x-xpixmap",
  264.             "xwd" => "image/x-xwindowdump",
  265.             "z" => "application/x-compress",
  266.             "zip" => "application/zip");
  267.     }
  268.    
  269.     /**
  270.      * Funcion para verificar si hay filtro por extension o no
  271.      *
  272.      * @return boolean
  273.      */
  274.     private function verificarExtension() {
  275.         $flag = true;
  276.  
  277.         if (is_array($this->extension) && count($this->extension) == 0) {
  278.             $flag = false;
  279.         } else if ($this->extension == '') {
  280.             $flag = false;
  281.         }
  282.         return $flag;
  283.     }
  284.    
  285.     /**
  286.      * Funcion final para subir archivo
  287.      *
  288.      * @param string $var -> nombre del input del archivo que cargará
  289.      * @param boolean $hash -> Si el nombre debe generar un aleatorio
  290.      * @return array -> Mensajes de error y/o success
  291.      */
  292.     public function subirArchivo($var, $hash = true) {
  293.         if (isset($_FILES[$var]) && count($_FILES[$var]) > 0) {
  294.             $destino = substr($this->carpeta, -1, 1) != '/' ? $this->carpeta . '/' : $this->carpeta;
  295.            
  296.             $tipo = $_FILES[$var]['type'];
  297.             $peso = $_FILES[$var]['syze'];
  298.             $nombre_tmp = $_FILES[$var]['tmp_name'];
  299.             $nombre = $_FILES[$var]['name'];
  300.             $extension = strtolower(end(explode('.', $nombre)));
  301.  
  302.             if ($this->verificarExtension()) {
  303.                 if (in_array($extension, $this->extension) === false) {
  304.                     $this->mensajes['errores'][] = array('codigo' => '059', 'titulo' => 'Extensión invalida', 'mensaje' => 'El archivo no corresponde a ninguna de las extensiones permitidas: Extensión del archivo: ' . $extension . ', permitidas: ' . implode(', ', $this->extension));
  305.                 } else if ($tipo != $this->type[$extension]) {
  306.                     $this->mensajes['errores'][] = array('codigo' => '219', 'titulo' => 'Tipo de archivo invalido', 'mensaje' => 'El tipo de archivo no es válido. Según la extensión (' . $extension . ') debe ser ' . $this->type[$extension] . ' y  se obtuvo ' . $tipo);
  307.                 }
  308.             }
  309.  
  310.             if ($peso > $this->maxLength) {
  311.                 $this->mensajes['errores'][] = array('codigo' => '521', 'titulo' => 'Exceso de tamaño', 'mensaje' => 'El tamaño del archivo debe ser menor que ' . floor($this->maxLength / 1024) . ' y el archivo pesa ' . floor($peso / 1024));
  312.             }
  313.  
  314.             if (empty($this->mensajes['errores'])) {
  315.                 if ($hash) {
  316.                     $ruta_destino = $destino . $this->generarNombre($nombre);
  317.                 } else {
  318.                     $ruta_destino = $destino . preg_replace("/ /", "_", $nombre);
  319.                 }
  320.                 if (move_uploaded_file($nombre_tmp, $ruta_destino)) {
  321.                     $this->mensajes['success'] = array('cargado' => 1, 'mensaje' => 'El archivo se ha cargado satisfactoriamente.', 'url' => $ruta_destino);
  322.                 } else {
  323.                     $this->mensajes['errores'][] = array('codigo' => '777', 'titulo' => 'Archivo no movido', 'mensaje' => 'No se ha cargado un archivo con la variable ' . $var . ' revise permisos en el directorio.');
  324.                 }
  325.             }
  326.         } else {
  327.             $this->mensajes['errores'][] = array('codigo' => '000', 'titulo' => 'Archivo Invalido', 'mensaje' => 'No se ha cargado un archivo con la variable ' . $var);
  328.         }
  329.        
  330.         return $this->mensajes;
  331.     }
  332.    
  333.     /**
  334.      * Funcion para generar nombre aleatorio siempre y cuando la variable $hash de Subir archivo este en true
  335.      *
  336.      * @global object $aplicacion
  337.      * @param string $nombre_archivo
  338.      * @return string
  339.      */
  340.     private function generarNombre($nombre_archivo) {
  341.         $rand = microtime() . '-' . mt_srand(time());
  342.         $hash = sha1(md5($rand));
  343.  
  344.         $nombre = $hash . '-' . preg_replace("/ /", "_", $nombre_archivo);
  345.         return $nombre;
  346.     }
  347.  
  348. }
Advertisement
Add Comment
Please, Sign In to add comment