Enviar mensagem ao usuário trabalhando com as opções do php.ini
Veremos como enviar uma mensagem amigável de “Este arquivo excede o tamanho permitido” (ou algo parecido) quando se permite upload via POST de determinados arquivos na aplicação/site em PHP.
[ Hits: 1.420 ]
Por: Buckminster em 26/11/2024
<!DOCTYPE html> <html lang="pt-br" class="no-js"> <head> <title>Upload de Arquivos</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- remove this if you use Modernizr --> <script> (function(e,t,n) { var r=e.querySelectorAll("html")[0];r.className=r.className.replace(/(^|\s)no-js(\s|$)/,"$1js$2"); }) (document,window,0); </script> <script>javascript:window.history.forward(0);</script> <script> if (window.history.replaceState) { window.history.replaceState(null, null, window.location.href); } </script> <style> #tudo{ margin-top:3%; alignment-adjust:middle; vertical-align:middle; text-align:center;/* "remédio" para o hack do IE */ } /* Esconde o input */ input[type='file'] { /*display: none;*/ width: 0; height: 0; opacity: 0; } /* Aparência que terá o seletor de arquivo */ label { background-color: #3498db; border-radius: 5px; color: #fff; cursor: pointer; margin: 10px; padding: 6px 20px; } #enviar_arquivo{ background-color:#00ff7f; border-color:#00ff7f; border-radius:5px; cursor: pointer; } </style> </head> <body> <div id="tudo" class="container">Upload de Arquivos<br>É permitido somente arquivo PDF com, no máximo, 2MB.<br>Arquivo PDF com texto e imagem, será lido somente o texto.<br><br> <!-- O tipo de encoding de dados, enctype, DEVE ser especificado abaixo --> <form id="form2" name="form2" enctype="multipart/form-data" action="upload.php" method="post"> <!--O input hidden com MAX_FILE_SIZE deve preceder o campo input file--> <input type="hidden" name="MAX_FILE_SIZE" value="2097152"><!-- Setar "upload_max_filesize" no php.ini --> <!-- O Nome do elemento input determina o nome da array $_FILES accept="application/pdf" --> <!--input type="file" name="arquivo" id="arquivo" accept="application/pdf,.pdf"--> <input type="file" name="arquivo" id="arquivo" class="inputfile" accept="application/pdf,.pdf"> <label for="arquivo"> <span>Selecione um arquivo</span> </label><br><br> <input type="submit" name="enviar_arquivo" id="enviar_arquivo" value="Enviar"> </form> </div> <!--Fim div tudo--> <script src="./customiza.js"></script> </body> </html>O arquivo customiza.js faz a troca dos dizeres Selecione um arquivo pelo nome do arquivo selecionado.
// Início 'use strict'; ;( function ( document, window, index ) { var inputs = document.querySelectorAll( '.inputfile' ); Array.prototype.forEach.call( inputs, function( input ) { var label = input.nextElementSibling, labelVal = label.innerHTML; input.addEventListener( 'change', function( e ) { var fileName = ''; if( this.files && this.files.length > 1 ) fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length ); else fileName = e.target.value.split( '\\' ).pop(); if( fileName ) label.querySelector( 'span' ).innerHTML = fileName; else label.innerHTML = labelVal; }); // Firefox bug fix input.addEventListener( 'focus', function(){ input.classList.add( 'has-focus' ); }); input.addEventListener( 'blur', function(){ input.classList.remove( 'has-focus' ); }); }); }( document, window, 0 )); //FimO arquivo upload.php faz o trabalho pesado.
<?php if(!isset($_SESSION) || (session_status() == PHP_SESSION_NONE) || (session_status() !== PHP_SESSION_ACTIVE) || (session_id() === "" )) { session_start(); } $_SESSION = array(); session_unset(); session_destroy(); //require_once 'D:/www/caminho/do/projetoMSG/pdfparser-master/pdfparser-master/alt_autoload.php'; //$uploaddir = 'D:/www/caminho/do/projetoMSG/upload/'; require_once '/var/www/html/projetoMSG/pdfparser-master/pdfparser-master/alt_autoload.php'; $uploaddir = '/home/caminho/do/projetoMSG/upload/'; //Sete os parâmetros 'post_max_size' e 'upload_max_filesize' com o mesmo valor no php.ini. //Recebe o dado necessário do formulário: $dados = filter_input(INPUT_SERVER,'CONTENT_LENGTH'); //$enviar = filter_input(INPUT_POST, 'enviar_arquivo', FILTER_UNSAFE_RAW); // //Função que converte string em bytes: function convertToBytes($string) { $unit = strtoupper(substr($string, -1)); $value = substr($string, 0, -1); switch($unit) { case 'K': return $value * 1024; case 'M': return $value * 1024 * 1024; case 'G': return $value * 1024 * 1024 * 1024; default: return $value; } } // Converte a string 'XM' (X é um número) do php.ini em bytes usando a função convertToBytes: $uploadmaximo = ini_get('upload_max_filesize'); $bytesup = convertToBytes($uploadmaximo); //$postmaximo = ini_get('post_max_size'); //$bytespost = convertToBytes($postmaximo); //Convertendo $dados para array: $value = (array)$dados; /*var_dump($_FILES['arquivo']['size']);*/ $arquivos = (!empty($_FILES['arquivo'])); switch($arquivos) { case (!empty($arquivos['size']) > (2097152)): //2MB echo "Este arquivo excede o tamanho de 2MB!"; break; } //var_dump($uploadmaximo); //var_dump($postmaximo).'<br>'; //var_dump($bytesup); //var_dump($value); //Selecionando o elemento desejado no array: //$element = (array_values($value)); //Verifica se a variável $value está vazia e envia para a página inicial caso o usuário der um refresh na página: if (empty($value[0])) { header("Location: index.html"); exit(); } //Verifica se o tamanho do arquivo é superior ao limite do php.ini e envia mensagem: if ($value[0] > $bytesup) { //echo "<p style='color: #f00;'>Este arquivo excede o tamanho de 2MB!</p>"; include_once 'index.html'; echo "<style> #tudo { animation:fadeInAnimation ease 2s; animation-iteration-count:1; animation-fill-mode:none; } @keyframes fadeInAnimation { 0% { opacity:0; } 50% { opacity:0; } 100% { opacity:1; } } .captcentro{ position:fixed; margin:0 auto; top:20.5%; left:50%; transform:translate(-50%, -50%); animation:hideAnimation 0s ease-in 4s; animation-fill-mode:forwards; border:2px solid #fff; padding:15px; background-color:#000000; border-radius:10px; font-size:20px; text-align:center; /*text-decoration:underline white;*/ } @keyframes hideAnimation { to { visibility:hidden; width:0; height:0; } } @media only screen and (max-width:576px) { .captcentro{ /*width:280px;*/ position:fixed; margin:0 auto; top:19.5%; left:50%; transform:translate(-50%, -50%); animation:hideAnimation 0s ease-in 4s; animation-fill-mode:forwards; border:2px solid #fff; padding:10px; background-color:#000000; border-radius:10px; font-size:16px; text-align:center; /*text-decoration:underline white;*/ } @keyframes hideAnimation { to { visibility:hidden; width:0; height:0; } } } </style>"; //header("Refresh: 0"); echo "<div class='captcentro'><span style='color:red; font-size:20px;'><b>O arquivo excede o tamanho de 2MB!</b></span></div>"; //header("Refresh: 0; url=pagina2.php"); exit(); } $arquivo = $_FILES['arquivo']; //var_dump($arquivo); //Verifica se o arquivo é PDF: if (($arquivo['type'] === '.pdf') or ($arquivo['type'] === 'application/pdf') or ($value[0]) === ($value)) { //Captura a exceção da classe Parser do PDFParser e envia mensagem amigável ao usuário: try { $parser = new \Smalot\PdfParser\Parser(); //var_dump($parser); //$pdf = $parser->parseFile($_FILES['arquivo']['tmp_name']); $pdf = $parser->parseContent(file_get_contents($_FILES['arquivo']['tmp_name'])); $text = $pdf->getText(); } catch (Exception $e) { //echo "<p style='color: #f00;'>Este arquivo está corrompido, vazio ou protegido!<br>Tente outro arquivo.</p>"; // $e->getMessage(), "\n"; include_once 'index.html'; echo "<style> #tudo { animation:fadeInAnimation ease 2s; animation-iteration-count:1; animation-fill-mode:none; } @keyframes fadeInAnimation { 0% { opacity:0; } 50% { opacity:0; } 100% { opacity:1; } } .captcentro{ position:fixed; margin:0 auto; top:20.5%; left:50%; transform:translate(-50%, -50%); animation:hideAnimation 0s ease-in 4s; animation-fill-mode: forwards; border:4px solid #ffffff; padding:15px; background-color:#ffff00; border-radius:10px; font-size:20px; text-align:center; /*text-decoration:underline white;*/ } @keyframes hideAnimation { to { visibility: hidden; width:0; height:0; } } @media only screen and (max-width:576px) { .captcentro{ /*width:280px;*/ position:fixed; margin:0 auto; top:19.5%; left:50%; transform:translate(-50%, -50%); animation:hideAnimation 0s ease-in 4s; animation-fill-mode:forwards; border:4px solid #ffffff; padding:10px; background-color:#ffff00; border-radius:10px; font-size:16px; text-align:center; /*text-decoration:underline white;*/ } @keyframes hideAnimation { to { visibility:hidden; width:0; height:0; } } } </style>"; echo "<div class='captcentro'><span style='color:red;'><b>O arquivo está corrompido, vazio ou protegido!</b></span></div>"; exit(); } //Verifica se o arquivo foi enviado por POST: if (is_uploaded_file($_FILES['arquivo']['tmp_name'])) { if (!is_dir($uploaddir)) { mkdir($uploaddir); } $uploadfile = $uploaddir . ($_FILES['arquivo']['name']); $parser = new \Smalot\PdfParser\Parser(); //var_dump($parser); //$pdf = $parser->parseFile($_FILES['arquivo']['tmp_name']); $pdf = $parser->parseContent(file_get_contents($_FILES['arquivo']['tmp_name'])); $text = $pdf->getText(); //echo $text; //Move o arquivo temporário para a pasta de destino: move_uploaded_file($_FILES['arquivo']['tmp_name'], $uploadfile); //echo "<p style='color: #f00;'>O arquivo ". $_FILES['arquivo']['name'] ." foi enviado com sucesso!</p>\n<br><br>"; require_once 'index.html'; echo "<style> #tudo { animation:fadeInAnimation ease 2s; animation-iteration-count:1; animation-fill-mode:none; } @keyframes fadeInAnimation { 0% { opacity:0; } 50% { opacity:0; } 100% { opacity:1; } } .captcentro{ position:fixed; margin:0 auto; top:20.5%; left:50%; transform:translate(-50%, -50%); animation:hideAnimation 0s ease-in 4s; animation-fill-mode:forwards; border:2px solid #ffffff; padding:15px; background-color:#ffd700; border-radius:10px; font-size:20px; text-align:center; /*text-decoration:underline white;*/ } @keyframes hideAnimation { to { visibility:hidden; width:0; height:0; } } @media only screen and (max-width:576px) { .captcentro{ /*width:280px;*/ position:fixed; margin:0 auto; top:19.5%; left:50%; transform:translate(-50%, -50%); animation:hideAnimation 0s ease-in 4s; animation-fill-mode:forwards; border:2px solid #ffffff; padding:10px; background-color:#ffd700; border-radius:10px; font-size:16px; text-align:center; /*text-decoration:underline white;*/ } @keyframes hideAnimation { to { visibility:hidden; width:0; height:0; } } } </style>"; echo "<div class='captcentro'><span style='color:red; font-size:20px;'><b>O arquivo ". $_FILES['arquivo']['name'] ." foi enviado com sucesso!</b></span></div>"; exit(); } exit(); } //Verifica se o tamanho do arquivo é menor ou igual ao limite do php.ini e exibe mensagem: if (($arquivo['size'] !== 0) or ($value[0]) === ($arquivo['size'])) { if (($arquivo['type'] !== '.pdf') or ($arquivo['type'] !== 'application/pdf')) { //echo "<p style='color: #f00;'>Este arquivo não é PDF!</p>"; include_once 'index.html’; echo "<style> #tudo { animation:fadeInAnimation ease 2s; animation-iteration-count:1; animation-fill-mode:none; } @keyframes fadeInAnimation { 0% { opacity:0; } 50% { opacity:0; } 100% { opacity:1; } } .captcentro{ position:fixed; margin:0 auto; top:20.5%; left:50%; transform:translate(-50%, -50%); animation:hideAnimation 0s ease-in 4s; animation-fill-mode:forwards; border:2px solid #fff; padding:15px; background-color:#000000; border-radius:10px; font-size:20px; text-align:center; /*text-decoration:underline white;*/ } @keyframes hideAnimation { to { visibility:hidden; width:0; height:0; } } @media only screen and (max-width:576px) { .captcentro{ /*width:280px;*/ position:fixed; margin:0 auto; top:19.5%; left:50%; transform:translate(-50%, -50%); animation:hideAnimation 0s ease-in 4s; animation-fill-mode:forwards; border:2px solid #fff; padding:10px; background-color:#000000; border-radius:10px; font-size:16px; text-align:center; /*text-decoration:underline white;*/ } @keyframes hideAnimation { to { visibility:hidden; width:0; height:0; } } } </style>"; echo "<div class='captcentro'><span style='color:red;'><b>O arquivo não é PDF!</b></span></div>"; exit(); } } //Condição que envia mensagem e chama o 'index.html' caso o usuário clicar no botão enviar sem selecionar arquivo: if (($value[0]) !== ($arquivo['size'])) { header("Location: index.html"); exit(); }
Entendendo o que é URI, URL, URN e conhecendo as diferenças entre POST e GET
Tradução do artigo do filósofo Gottfried Wilhelm Leibniz sobre o sistema binário
Compilação do Squid 3 no Debian Wheezy
ClamAV, o kit de ferramentas antivírus
Gerando documentos PDF com a classe FPDF no PHP
Upload de imagens com criação de thumbnails em PHP
O perigo no gerenciador de uploads do PHP
PEAGLE: Serviço Web de busca indexada em seu servidor local
Trabalhando com arquivos em PHP
Armazenando a senha de sua carteira Bitcoin de forma segura no Linux
Enviar mensagem ao usuário trabalhando com as opções do php.ini
Meu Fork do Plugin de Integração do CVS para o KDevelop
Compartilhando a tela do Computador no Celular via Deskreen
Como Configurar um Túnel SSH Reverso para Acessar Sua Máquina Local a Partir de uma Máquina Remota
Encontre seus arquivos facilmente com o Drill
Mouse Logitech MX Ergo Advanced Wireless Trackball no Linux
Compartilhamento de Rede com samba em modo Público/Anônimo de forma simples, rápido e fácil
Cups: Mapear/listar todas as impressoras de outro Servidor CUPS de forma rápida e fácil
Forum Linux Mint bloqueado para o Brasil (3)
Ferramenta para identificação de audio [RESOLVIDO] (10)
Configuração de Proxy - Squid (2)