Skip to content

Instantly share code, notes, and snippets.

@DanielHe4rt
Created May 8, 2021 19:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanielHe4rt/0f11bd10af1171f13c86e6d40658f79b to your computer and use it in GitHub Desktop.
Save DanielHe4rt/0f11bd10af1171f13c86e6d40658f79b to your computer and use it in GitHub Desktop.
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