Skip to content

Instantly share code, notes, and snippets.

@Chavao
Created August 6, 2012 01:30
Show Gist options
  • Save Chavao/3268874 to your computer and use it in GitHub Desktop.
Save Chavao/3268874 to your computer and use it in GitHub Desktop.
File uploader for Cake PHP
<?php
class FileUploadComponent extends Component {
public $allowedTypes;
public $maxSize;
private $tmpFile;
public $uploadPath;
public function __construct() {
$this->allowedTypes = array();
$this->maxSize = 5 * 1024 * 1024;
$this->uploadPath = APP . DIRECTORY_SEPARATOR . "upload" . DIRECTORY_SEPARATOR;
}
private function validateTypes() {
return (in_array($this->tmpFile['type'], $this->allowedTypes));
}
private function validateSize() {
return (filesize($this->tmpFile['tmp_name']) < $this->maxSize);
}
public function upload($file) {
$this->tmpFile = $file;
if($this->tmpFile['error']) {
throw new Exception("Image not sent");
}
if(!$this->validateTypes()) {
throw new Exception("File type not allowed");
}
if(!$this->validateSize()) {
throw new Exception("File size is larger than allowed");
}
$extension = end(explode(".", $this->tmpFile['name']));
$tmpUploadName = md5($this->tmpFile['name'].time()) . "." . $extension;
if(!move_uploaded_file($this->tmpFile['tmp_name'], $this->uploadPath . $tmpUploadName)) {
throw new Exception("Unknown error");
}
return $tmpUploadName;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment