Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Uploader de Arquivos em PHP
<?php
session_start();
class FileUploader {
private $file;
private $mimesAllowed = [];
public function upload($file, string $directory = '') {
$this->setFile($file);
if (!$this->validateMimeType()) {
throw new Exception('irmão para');
}
$filename = $directory . $this->generateFileName();
return move_uploaded_file($this->file['tmp_name'], $filename);
}
private function validateMimeType() {
$mime = $this->getMimeType();
return in_array($mime, $this->mimesAllowed);
}
private function getMimeType() {
$mimes = explode('.', $this->file['name']);
if (!$mimes) {
throw new Exception('namoral coloca um arquivo q tenha uma extensão valida.');
}
return array_pop($mimes);
}
public function setMimesAllowed(array $mimeTypes) {
$this->mimesAllowed = $mimeTypes;
}
private function setFile($file) {
$this->file = $file;
}
private function generateFileName() {
return md5(time()) . '.' . $this->getMimeType();
}
}
$uploader = new FileUploader($_FILES['image']);
$uploader->setMimesAllowed(['png', 'jpg', 'gif']);
try {
if ($uploader->upload($_FILES['image'])) {
echo "foi";
} else {
echo "deu ruim no server";
}
} catch(Exception $e) {
var_dump($e->getMessage());
if(isset($_SESSION['errors'])) {
$_SESSION['errors'] += 1;
} else {
$_SESSION['errors'] = 1;
}
if($_SESSION['errors'] >= 3) {
header("Location: https://www.youtube.com/watch?v=dQw4w9WgXcQ");
}
}
var_dump($_SESSION);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment