Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

TheNight

File size com move_uploaded_file

Recommended Posts

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;
		}
	}
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

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;
		}
	}
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

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

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.