Created
August 6, 2012 01:30
-
-
Save Chavao/3268874 to your computer and use it in GitHub Desktop.
File uploader for Cake PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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