note 89374 modified in features.file-upload.errors by danbrown

From: Date: Thu, 05 Mar 2009 02:46:26 +0000
Subject: note 89374 modified in features.file-upload.errors by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-151498@lists.php.net to get a copy of this message
[EDIT BY danbrown AT php DOT net: This code is a fixed version of a note originally submitted by (Thalent, Michiel Thalen) on 04-Mar-2009.] This is a handy exception to use when handling upload errors: <?php class UploadException extends Exception { public function __construct($code) { $message = $this->codeToMessage($code); parent::__construct($message, $code); } private function codeToMessage($code) { switch ($code) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break; default: $message = "Unknown upload error"; break; } return $message; } } // Use if ($_FILES['file']['error'] === UPLOAD_ERR_OK) { //uploading successfully done } else { throw new UploadException($_FILES['file']['error']); } ?> --was-- Thanks Michiel for the great code! When I tried it I found it was missing a return statement so here it is with the return statement added: <?php class UploadException extends Exception { public function __construct($code) { $message = $this->codeToMessage($code); parent::__construct($message, $code); } private function codeToMessage($code) { switch ($code) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break; default: $message = "Unknown upload error"; break; } return $message; } } // Use if ($_FILES['file']['error'] === UPLOAD_ERR_OK) { //uploading successfully done } else { throw new UploadException($_FILES['file']['error']); } ?> http://php.net/manual/en/features.file-upload.errors.php

« previous php.notes (#151498) next »