Upload Error Handler

There are 2 configs in php.ini related to upload process:

  • post_max_size
  • upload_max_filesize

If the size of your post is over post_max_size, system could cause an error without any warning and $_POST could be empty for no reason. So it’s important to check post size before you start to process a form submit.

Helper functions:

    function return_bytes($val)
    {
        $val  = trim($val);

        if (is_numeric($val))
            return $val;

        $last = strtolower($val[strlen($val)-1]);
        $val  = substr($val, 0, -1); // necessary since PHP 7.1; otherwise optional

        switch($last) {
            // The 'G' modifier is available since PHP 5.1.0
            case 'g':
                $val *= 1024;
            case 'm':
                $val *= 1024;
            case 'k':
                $val *= 1024;
        }

        return $val;
    }

    public function check_post_size(){
        $max_size = $this->return_bytes(ini_get('post_max_size'));
        $content_length = $_SERVER['CONTENT_LENGTH'];
        if($content_length > $max_size){
            $this->err = '送出的資料大於限制: ' . ini_get('post_max_size');
            return false;
        }

        return true;
    }

    public function check_upload_error($field_name){
        $file = $_FILES[$field_name];
        if($file['error'] != 0){
            $this->err = $this->get_upload_error($file['error']);
            return false;
        }

        return true;
    }

    function get_upload_error($error){
		$err = '';
		switch($error){
			case 1:
				$err = '上傳的檔案超過限制:' . ini_get('upload_max_filesize');
				break;
			case 2:
				$err = 'File size exceed the limit(2)';
				break;
			case 3:
				$err = 'File is not uploaded completely';
				break;
			case 4:
				$err = 'Please upload a file';
				break;
			case 6:
				$err = 'Missing a temporary folder';
				break;
			case 7:
				$err = 'Failed to write file to disk';
				break;
			case 8:
				$err = 'Unknown extension issue';
				break;
			case 9://Added by Rex
				$err = 'Custom Error';
				break;
		}

		return $err;
	}

Other programming issue:

//If related to Upload_lib.php, make sure following values are big enough
$config['max_size']	= '9999';
$config['max_width']  = '9999';
$config['max_height']  = '9999';

//Image_handler.php
//If memory is not enough, this line could cause error:
imagecreatefromjpeg($file);