2008年6月11日 星期三

php上傳物件

參考網址

http://www.devshed.com/c/a/PHP/Developing-a-Modular-Class-For-a-PHP-File-Uploader/1/


檔案上傳物件

上列網址是一個檔案上傳物件的實例,用了一些php內建的函數及物件,使用內建函數及物件,執行效率會提高(因為是用c寫的),程式內也用了迴圈的方式把全域陣列$_FILE中的key/value都對應到物件中的屬性,這樣就不用寫一堆討人厭的$_FILE['userfile']['name']這類一長串不好輸入的字元,整個程式碼很清爽。

撰寫這個物件的背景知識

使用的函數及物件
Exception物件
in_array()函數
move_uploaded_file()函數

使用的全域陣列
$_FILE['userfile']['name'] 原始檔名
$_FILE['userfile']['tmp_name'] 儲在server上的暫存檔名
$_FILE['userfile']['type'] 檔案的mime型態
$_FILE['userfile']['size'] 檔案大小,單位是byte
$_FILE['userfile']['error'] 上傳錯誤,錯誤代碼查php manual就知道了


從上列網址post上來的上傳物件的範例程式碼


class FileUploader{

private $uploadFile;

private $name;

private $tmp_name;

private $type;

private $size;

private $error;

private $allowedTypes=array
('image/jpeg','image/gif','image/png','text/plain','application/ms-word');

public function __construct($uploadDir='C:uploaded_files'){

if(!is_dir($uploadDir)){

throw new Exception('Invalid upload directory.');

}

if(!count($_FILES)){

throw new Exception('Invalid number of file upload parameters.');

}

foreach($_FILES['userfile'] as $key=>$value){

$this->{$key}=$value;

}

if(!in_array($this->type,$this->allowedTypes)){

throw new Exception('Invalid MIME type of target file.');

}

$this->uploadFile=$uploadDir.basename($this->name);

}

// upload target file to specified location

public function upload(){

if(move_uploaded_file($this->tmp_name,$this->uploadFile)){

return true;

}

// throw exception according to error number

switch($this->error){

case 1:

throw new Exception('Target file exceeds maximum allowed size.');

break;

case 2:

throw new Exception('Target file exceeds the MAX_FILE_SIZE value specified on the upload form.');

break;

case 3:

throw new Exception('Target file was not uploaded completely.');

break;

case 4:

throw new Exception('No target file was uploaded.');

break;

case 6:

throw new Exception('Missing a temporary folder.');

break;

case 7:

throw new Exception('Failed to write target file to disk.');

break;

case 8:

throw new Exception('File upload stopped by extension.');

break;

}

}

}

?>



物件使用範例




try{

if($_POST['send']){

require_once 'fileuploader.php';

$fileUploader=new FileUploader();

if($fileUploader->upload()){

echo 'Target file uploaded successfully!';

}

}

}




catch(Exception $e){

echo $e->getMessage();

exit();

}

?>

沒有留言: