Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Olá pessoal, estou com dúvida quanto a adicionar verificação de file size nesta class, alguém poderia como me dar uma ajuda?
Fiz esta classe mas acabei que ficar sem lógica ou não me programei antes de começar a montar a classe:
<?php
class Upload {
private $_supportedFormats = ['image/jpg', 'image/jpeg', 'image/png'];
private function encryption($str) {
return md5($str);
}
private function verify_file($file) {
if (is_array($file)) {
return true;
} else {
return false;
}
}
private function verify_format($file) {
if ($this->verify_file($file)) {
if (in_array($file['type'], $this->_supportedFormats)) {
return true;
}
} else {
return false;
}
}
public function upload_file($file) {
if ($this->verify_format($file)) {
move_uploaded_file($file['tmp_name'], FOLDER_UPLOADS . '/' . $this->encryption($file['name']) . '.' . pathinfo($file['name'],PATHINFO_EXTENSION));
return true;
} else {
return false;
}
}
}Ok, eu já sabia só estava sem lógica, então criei um método para verificar o size, vou tentar adapta-lo para printar uma mensagem quando o tamanho for excedido:
<?php
class Upload {
private $_supportedFormats = ['image/jpg', 'image/jpeg', 'image/png'];
private function encryption($str) {
return md5($str);
}
private function verify_file($file) {
if (is_array($file)) {
return true;
} else {
return false;
}
}
private function verify_format($file) {
if ($this->verify_file($file)) {
if (in_array($file['type'], $this->_supportedFormats)) {
return true;
}
} else {
return false;
}
}
private function verify_size($file) {
$file_size = $file['size'];
if ($file_size > 2097152) {
return false;
} else {
return true;
}
}
public function upload_file($file) {
if ($this->verify_format($file)) {
if ($this->verify_size($file)) {
move_uploaded_file($file['tmp_name'], FOLDER_UPLOADS . '/' . $this->encryption($file['name']) . '.' . pathinfo($file['name'],PATHINFO_EXTENSION));
} else {
return false;
}
return true;
} else {
return false;
}
}
}Você pode, por exemplo, retornar uma mensagem de erro em vez de false.
Quando for testar o retorno do método, use "===", desta forma:
if (($status = $this->verify_size($file)) === true)
{
// ok
}
else
{
echo "Erro: " . $status;
}
O "===" garante que é booleano true. Caso contrário, será uma string com o erro
Você deve verificar o índice 'size' do array $_FILES, que armazena o tamanho do arquivo em bytes
Veja: http://php.net/manual/pt_BR/features.file-upload.post-method.php