file = null; $this->upload_max_size = ini_get('upload_max_filesize'); $this->post_max_size = ini_get('post_max_size'); } public function run($target_dir) { $res = $this->init(); if (!$res["success"]) return $res; if ( ($error_code = $this->file['error']) != UPLOAD_ERR_OK ) return array( "success" => false, "error" => $this->getUploadErrorMessage($error_code) ); $fileName = $this->file['name']; $fileTmp = $this->file['tmp_name']; if( !is_uploaded_file($fileTmp) ) return array( "success" => false, "error" => 'Error uploading file - unknown error.' ); $movedFile = time().'_'.$this->generateRandomString().'_'.basename( $fileName ); $target_path = $target_dir.$movedFile; if( !move_uploaded_file($fileTmp, $target_path) ) return array( "success" => false, "error" => 'Error uploading file - could not save uploaded file - Internal error' ); return array( "success" => true, "fileName" => $movedFile ); } private function init() { $this->file = null; if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0) return array( "success" => false, "error" => 'Error uploading file - Posted data is too large (limitation to '.$this->post_max_size.')' ); if (!isset($_FILES['sourcefile'])) return array( "success" => false, "error" => 'Error uploading file - cannot get source file' ); $this->file = $_FILES['sourcefile']; return array( "success" => true ); } private function getUploadErrorMessage($error) { $message = 'Error uploading file - '; switch($error) { case UPLOAD_ERR_OK: $message = false; break; case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $message .= 'file too large (limitation to '.$this->upload_max_size.')'; break; case UPLOAD_ERR_PARTIAL: $message .= 'file upload not completed.'; break; case UPLOAD_ERR_NO_FILE: $message .= 'zero-length file uploaded.'; break; default: $message .= 'internal error #'.$error; break; } return $message; } private function generateRandomString($length = 10) { return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); } } $upMgr = new UploadManager(); $r = $upMgr->run(TREPS_PHP_TMP_DIR); echo json_encode($r); ?>