Avaliação de classe
Olá pessoas!
Desde a semana passada estava trabalhando nessa classe. Hoje terminei (mas será melhorada no futuro).
Gostariam de saber o que acharam :grin:/>
Com ela é permitido:
- Escolher o tipo de arquivo permitido para upload, desde as extensões até o tipo
- Fazer o redimensionamento de imagens
- Definir o tamanho máximo do arquivo (em KB, MB e GB)
- Definir a pasta para o upload ser direcionado
- Definir o nome do arquivo
- Definir, se caso a função de redimensionamento for chamada, se só será feito o upload da imagem redimensionada ou da normal e dela.
- Gerar o nome da imagem, com diretório ou sem (Ex: com dir: path/file.ext ; sem dir: file.ext)
<?php
class Upload{
/**
* Upload de arquivos
* @author Gabriel Jacinto
*/
/**
* Dados do arquivo
* @var $file = recebe o arquivo
* @var $name = recebe o nome da imagem
* @var $tmpName = recebe o tmp_name do arquivo
* @var $size = recebe o tamanho (kb) do arquivo
* @var $sizeMax = define o tamanho máximo do arquivo
* @var $ext = recebe a extensão do arquivo
* @var $directoryFinal = define o diretório (+ nome) para onde o arquivo sereá enviado e com que nome
* @var $errors = recebe os erros do arquivo
* @var $path = pasta para onde o arquivo será mandado
*/protected
$file,
$name,
$nameMiniature,
$tmpName,
$size,
$sizeMax,
$ext,
$directoryFinal,
$directoryFinalMiniature,
$errors,
$typeFile,
$type,
$path = "uploads/";
/**
* Lista com possíveis erros do arquivo
* @var $this->errors = array : erros da imagem
*/
protected
$errorsList = array();
/**
* Constantes para dizer qual o tipo de arquivo permitido para upload
* @const IMAGE = somente imagens
* @const AUDIO = somente arquivos de audio
* @const VIDEO = somente arquivos de vídeo
* @const ALL = para qualquer arquivo
*/
const IMAGE = 'Image';
const AUDIO = 'Audio';
const VIDEO = 'Video';
const ALL = 'All';
/**
* @const ONLY_RESIZE = somente redimensionar
* @var $onlyResize = se true, somente o upload da imagem redimensionada será feito
*/
const ONLY_RESIZE = true;
protected $onlyResize;
/**
* @const WITH_DIR = retorna o diretório mais o nome da imagem (Ex: dir/file.ext)
* @const ONLY_NAME = retorna somente o nome da imagem (Ex: file.ext)
*/
const WITH_DIR = 'with_dir';
const ONLY_NAME = 'only_name';
/**
* Especificações para imagem
* @var $width = largura da imagem
* @var $height = altura da imagem
* @var $resizeImageToWidth = largura de nova imagem
* @var $resizeImageToHeight = altura da nova imagem
*/
protected
$width,
$height,
$resizeImageToWidth,
$resizeImageToHeight;
/**
* Pega as informações do arquivo enviado (método construtor)
* @param $file = arquivo a ser enviado
* @var $this->file = arquivo e armazana nessa mesma variável
* @method $this->setTmpName() = pega o tmp_name do arquivo e armazana na variável $this->tmpName
* @method $this->setName() = pega o nome do arquivo e armazena na variável $this->name
* @method $this->setExt() = pega a extensão do arquivo e armazena na variável $this->ext
*/
public function __construct( $file ){
$this->file = $file;
$this->searchErrors();
$this->setTmpName();
$this->setName();
$this->setTypeFile();
$this->setSize();
$this->setExt();
}
/**
* Trocando a para onde o arquivo será mandado
* @param $path = novo diretório
* @var $this->path = define um novo diretório para onde o arquivo será mandado (Original: 'uploads/')
*/
public function setPath( $path ){
$this->path = $path;
$this->setDirectoryFinal();
}
protected function setTypeFile(){
$this->typeFile = $this->file['type'];
}
/**
* Recebe o nome do arquivo
* @param string = novo nome da imagem
*/
public function setName( $name = null ){
if( $name != null ){
$this->name = $name . '.' . $this->ext;
$this->setDirectoryFinal();
}else{
$this->name = $this->file['name'];
$explode = explode( '.', $this->file['name'] );
$nameForMiniature = str_replace( end( $explode ), '', $this->file['name'] );
$nameForMiniature = str_replace( '.', '', $nameForMiniature );
$this->nameMiniature = $nameForMiniature . '_miniature.';
$this->setDirectoryFinal();
}
}
/**
* Retornará o nome do arquivo
* @param $name = com const's WITH_DIR ou ONLY_DIR
*/
public function getName( $name ){
if( $name == 'with_dir' ){
return $this->directoryFinal;
}elseif( $name == 'only_name' ){
return $this->name;
}
}
/**
* Retornará o nome da imagem redimensionada
* @param $name = com const's WITH_DIR ou ONLY_DIR
*/
public function getNameMiniature( $name ){
if( $name == 'with_dir' ){
return $this->directoryFinalMiniature;
}elseif( $name == 'only_name' ){
return $this->nameMiniature;
}
}/**
* Pega o tamanho do arquivo
* @var $this->size = onde será armazanado o tamanho do arquivo em KB's
*/
protected function setSize(){
$this->size = $this->file['size'];
}
/**
* Pega o tmp_name do arquivo
* @var $this->tmpName = onde o tmp_name do arquivo é armazanado
*/
protected function setTmpName(){
$this->tmpName = $this->file['tmp_name'];
}
/**
* Pega a exntensão do arquivo
* @var $this->ext = onde será armazenada a extensão do arquivo
*/
protected function setExt(){
$explode = explode( '.', $this->name );
$this->ext = end( $explode );
}
/**
* Cria o diretório final do arquivo a ser enviado
* @var $this->directoryFinal = str com o diretório
*/
protected function setDirectoryFinal(){
$this->directoryFinal = $this->path . $this->name;
$this->directoryFinalMiniature = $this->path . $this->nameMiniature . $this->ext;
}
/**
* Escolhe o tipo de arquivo a ser enviado
* @param $type = o tipo do arquivo a ser enviado (self::IMAGE, self::AUDIO, self::VIDEO)
* @param $allowed = tipos permitidos de arquivos (se for vazio, valores padrões são aplicados)
* @var $allowedForImages = array : tipos de imagens permitidas
* @var $allowedForAudio = array : tipos de arquivos de áudio permitidos
* @var $allowedForVideo = array : tipos de arquivos de vídeo permitidos
*/
public function typeAllowed( $type, array $allowed = null ){
$allowedForAll = array();
$allowedForImages = array( 'JPEG', 'jpeg', 'JPG', 'jpg', 'GIF', 'gif', 'PNG', 'png', 'BMP', 'bmp' );
$allowedForAudio = array( 'MP3', 'mp3', 'WMA', 'wma', 'AAC', 'aac', 'WMA', 'wma', 'OGG', 'ogg', 'AC3', 'ac3' );
$allowedForVideo = array( 'AVI', 'avi', 'WMV', 'wmv', 'MP4', 'mp4', 'FLV', 'flv' );
if( $allowed != null ){
switch( $type ){
case 'Image':
$allowedForImages = $allowed;
break;
case 'Audio':
$allowedForAudio = $allowed;
break;
case 'Video':
$allowedForVideo = $allowed;
break;
case 'All':
$allowedForAll = $allowed;
break;
}
}
switch( $type ){
case 'Image':
$this->type = 'image';
if( !array_search( $this->ext, $allowedForImages ) ){
die( "<script>alert('O arquivo não é uma imagem, por isso o upload foi cancelado.');</script>" );
}
break;
case 'Audio':
$this->type = 'audio';
if( !in_array( $this->ext, $allowedForAudio ) ){
die( "<script>alert('O arquivo não um arquivo de áudio, por isso o upload foi cancelado.');</script>" );
}
break;
case 'Video':
$this->type = 'video';
if( !in_array( $this->ext, $allowedForVideo ) ){
die( "<script>alert('O arquivo não é um arquivo de vídeo, por isso o upload foi cancelado.');</script>" );
}
break;
case 'All':
if( !in_array( $this->ext, $allowedForAll ) ){
die( "<script>alert('Tipo de arquivo inválido!');</script>" );
}
}
}
/**
* Define o tamanho máximo do arquivo a ser enviado
* @param $size_max = tamanho máximo (float)
* @param $type = tipo de unidade de medida ('KB', 'MB', 'GB')
*/
public function sizeMax( $size_max, $type ){
switch( strtolower( $type ) ){
case "kb":
$kb = $size_max;
$this->sizeMax = 1024 * $kb;
if( $this->sizeMax < $this->size ){
die( "O arquivo é muito grande, o máximo é ".$kb."KB" );
}
break;
case "mb":
$mb = $size_max;
$this->sizeMax = 1024 * 1024 * $mb;
if( $this->sizeMax < $this->size ){
die( "O arquivo é muito grande, o máximo é ".$mb."MB" );
}
break;
case "gb":
$gb = $size_max;
$this->sizeMax = 1024 * 1024 * 1024 * $gb;
if( $this->sizeMax < $this->size ){
die( "O arquivo é muito grande, o máximo é ".$gb."MB" );
}
break;
default:
die( "Unidade de medida de tamenho de arquivo inválida" );
break;
}
}
/**
* Redimensionamento da imagem
* @param $width = nova largura da imagem
* @param $height = nova altura da imagem
* @return caso tente ser feito o redimensionamento e o arquivo não for imagem, para
*/
public function resizeImage( $width, $height, $onlyResize = false ){
if( $this->type == 'image' or
strtolower($this->ext) == 'jpg' or
strtolower($this->ext) == 'jpeg' or
strtolower($this->ext) == 'gif' or
strtolower($this->ext) == 'png' or
strtolower($this->ext) == 'bmp' ) {
$this->type = 'image';
$this->onlyResize = $onlyResize;
$this->redirectImageToWidth = $width;
$this->redirectImageToHeight = $height;
}else{
die( 'Upload cancelado. Você não pode redimensionar arquivos que não sejam imagem' );
}
}
/**
* Verifica se há erros no arquivo
* @var $this->errors = fica armazanados os erros do arquivo
* @var $this->errorsList = erros em string (Erros by Thiago Belem (http://blog.thiagobelem.net))
* @return morre se huver erros
*/
protected function searchErrors(){
$this->errors = $this->file['error'];
$this->errorsList[0] = 'Não houve erro';
$this->errorsList[1] = 'O arquivo no upload é maior do que o limite do PHP';
$this->errorsList[2] = 'O arquivo ultrapassa o limite de tamanho especifiado no HTML';
$this->errorsList[3] = 'O upload do arquivo foi feito parcialmente';
$this->errorsList[4] = 'Não foi feito o upload do arquivo';
if( $this->errors != 0 ){
die( "<b>Ao fazer o upload, erros foram encontrados:</b> " . $this->errorsList[ $this->errors ] );
}
}
/**
* Faz o redimensionamento de imagens
*/
protected function actionResize(){
if ( $this->typeFile == "image/jpeg" ){
$img = imagecreatefromjpeg( $this->tmpName );
}elseif ( $this->typeFile == "image/gif" ){
$img = imagecreatefromgif( $this->tmpName );
}elseif ( $this->typeFile == "image/png" ){
$img = imagecreatefrompng( $this->tmpName );
}
$this->width = imagesx($img);
$this->height = imagesy($img);
$nova = imagecreatetruecolor( $this->redirectImageToWidth, $this->redirectImageToHeight );
imagecopyresampled($nova, $img, 0, 0, 0, 0, $this->redirectImageToWidth, $this->redirectImageToHeight, $this->width, $this->height );
if ( $this->typeFile == "image/jpeg" ){
if( imagejpeg( $nova, $this->directoryFinalMiniature ) ){
return true;
}
}else if ( $this->typeFile == "image/gif" ){
if( imagegif( $nova, $this->directoryFinalMiniature ) ){
return true;
}
}else if ( $this->typeFile == "image/png" ){
if( imagepng( $nova, $this->directoryFinalMiniature ) ){
return true;
}
}
}
/**
* Faz o upload do arquivo caso não haja erros
* @param $msg = mensagem de sucesso caso o arquivo seja enviado
* @var $upload = faz o upload do arquivo
*/
public function upload( $msgSucessCustom = null ){
$msgSucessDefault = "<script type=\"text/javascript\">alert( 'Upload realizado com sucesso!' );</script>";
if( $this->type == 'image' ){
if( $this->redirectImageToHeight != null and $this->redirectImageToWidth != null ){
if( $this->actionResize() ){
if( $this->onlyResize ){
if( $msgSucessCustom == null ){
echo $msgSucessDefault;
}else{
echo $msgSucessCustom;
}
}
}
}
}
if( !$this->onlyResize ){
$upload = move_uploaded_file( $this->tmpName, $this->directoryFinal );
if( $upload ){
if( $msgSucessCustom == null ){
echo $msgSucessDefault;
}else{
echo $msgSucessCustom;
}
}
}
}
}
?>
Para dar um exemplo de funcionamento com imagens:
$up = new Upload( $arquivo );
$up->setPath( 'imagens' );//Se esse método não for chamado, o arquivo irá para 'upload/'
$up->setName( 'file' );//Se esse método não for chamado, o arquivo irá com o nome original
$up->typeAllowed( Upload::IMAGE, array('jpg', 'gif') );/* self::AUDIO (para arquivos de áudio)
self::VIDEO (para arquivos de video)
self::ALL (para qualquer tipo)
OBS.: Esse método é opcional ($this->typeAllowed) e se o 1º parâmetro for self::ALL, apenas servirá para que você possa escolher a extensão do arquivo no segundo param em forma de array.
Se for IMAGE, ou AUDIO ou VIDEO, pode ser escolhida a extensão, mas haverá extensões padrão permitidos (como pode ser visto na class) */
$up->resizeImage( 200, 200 );/* Redimensiona a imagem para width: 200 / height: 200
Se for passado um terceiro param com self::ONLY_RESIZE, apenas o upload da imagem redimensionada será feito, senão, o da normal e o da redimensionada */
$up->sizeMax( '1', 'MB' );/* Será permitido arquivos de até 1 MB, mas pode se usar:
1 KB : sizeMax( 1 , 'KB' )
1 GB : sizeMax( 1 , 'GB' ) */
$up->upload( 'Upload realizado com sucesso!' );/* Realiza o upload
Se o parâmetro for passado em null, haverá uma mensagem padrão de sucesso
*/
~ Posso ter me perdido ao tentar explicar algo ~
Discussão (22)
Carregando comentários...