Tuesday, September 29, 2009

Detecting rejected file upload in PHP code

PHP can be configured to reject the file uploads exceeding some limit via upload_max_filesize server configuration parameter (in php.ini). As per the documentation here, even though the file upload is rejected, an entry is made in $_FILES array with error code set to UPLOAD_ERR_INI_SIZE. This is documented here.

Practically speaking this is not the case. When the uploaded content size exceed upload_max_filesize, $_FILES array is empty. This array cannot be inspected to find the reason for the error. I found a hack to do this.

* For file uploads, $_SERVER['CONTENT_TYPE'] is always set to multipart/form-data followed by the multipart boundary string.
* $_SERVER['CONTENT_LENGTH'] will be set to the content-length in the http header.

Combination of above 2 can be used to detect the file upload exceeding upload_max_filesize.

if ( stripos( $_SERVER['CONTENT_TYPE'], 'multipart/form-data') === 0 && intval($_SERVER['CONTENT_LENGTH']) > 0 &&
count($_FILES) == 0) {
error_log( 'File upload rejected due to file size exceeding upload_max_filesize limit' );

No comments:

Book Promotion