File data type in php

Handling file uploads

You’d better check $_FILES structure and values throughly.
The following code cannot cause any errors absolutely.

header ( ‘Content-Type: text/plain; charset=utf-8’ );

// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (
!isset( $_FILES [ ‘upfile’ ][ ‘error’ ]) ||
is_array ( $_FILES [ ‘upfile’ ][ ‘error’ ])
) throw new RuntimeException ( ‘Invalid parameters.’ );
>

// Check $_FILES[‘upfile’][‘error’] value.
switch ( $_FILES [ ‘upfile’ ][ ‘error’ ]) case UPLOAD_ERR_OK :
break;
case UPLOAD_ERR_NO_FILE :
throw new RuntimeException ( ‘No file sent.’ );
case UPLOAD_ERR_INI_SIZE :
case UPLOAD_ERR_FORM_SIZE :
throw new RuntimeException ( ‘Exceeded filesize limit.’ );
default:
throw new RuntimeException ( ‘Unknown errors.’ );
>

// You should also check filesize here.
if ( $_FILES [ ‘upfile’ ][ ‘size’ ] > 1000000 ) throw new RuntimeException ( ‘Exceeded filesize limit.’ );
>

// DO NOT TRUST $_FILES[‘upfile’][‘mime’] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo ( FILEINFO_MIME_TYPE );
if ( false === $ext = array_search (
$finfo -> file ( $_FILES [ ‘upfile’ ][ ‘tmp_name’ ]),
array(
‘jpg’ => ‘image/jpeg’ ,
‘png’ => ‘image/png’ ,
‘gif’ => ‘image/gif’ ,
),
true
)) throw new RuntimeException ( ‘Invalid file format.’ );
>

// You should name it uniquely.
// DO NOT USE $_FILES[‘upfile’][‘name’] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (! move_uploaded_file (
$_FILES [ ‘upfile’ ][ ‘tmp_name’ ],
sprintf ( ‘./uploads/%s.%s’ ,
sha1_file ( $_FILES [ ‘upfile’ ][ ‘tmp_name’ ]),
$ext
)
)) throw new RuntimeException ( ‘Failed to move uploaded file.’ );
>

echo ‘File is uploaded successfully.’ ;

Читайте также:  Css центрирование абсолютного блока

> catch ( RuntimeException $e )

IE on the Mac is a bit troublesome. If you are uploading a file with an unknown file suffix, IE uploads the file with a mime type of «application/x-macbinary». The resulting file includes the resource fork wrapped around the file. Not terribly useful.

The following code assumes that the mime type is in $type, and that you have loaded the file’s contents into $content. If the file is in MacBinary format, it delves into the resource fork header, gets the length of the data fork (bytes 83-86) and uses that to get rid of the resource fork.

(There is probably a better way to do it, but this solved my problem):

if ( $type == ‘application/x-macbinary’ ) <
if ( strlen ( $content ) < 128 ) die( 'File too small' );
$length = 0 ;
for ( $i = 83 ; $i $length = ( $length * 256 ) + ord ( substr ( $content , $i , 1 ));
>
$content = substr ( $content , 128 , $length );
>
?>

Your binary files may be uploaded incorrectly if you use modules what recode characters. For example, for Russian Apache, you should use

CharsetDisable On

Clarification on the MAX_FILE_SIZE hidden form field:

PHP has the somewhat strange feature of checking multiple «maximum file sizes».

The two widely known limits are the php.ini settings «post_max_size» and «upload_max_size», which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names «max_file_size» (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made — see bug #40387 — http://bugs.php.net/bug.php?id=40387) vague references to «allows browsers to check the file size before uploading». This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big — this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).

If no file is selected for upload in your form, PHP will return $_FILES[‘userfile’][‘size’] as 0, and $_FILES[‘userfile’][‘tmp_name’] as none.

As of PHP 4.2.0, the «none» is no longer a reliable determinant of no file uploaded. It’s documented if you click on the «error codes» link, but you need to look at the $_FILES[‘your_file’][‘error’]. If it’s 4, then no file was selected.

If «large files» (ie: 50 or 100 MB) fail, check this:

It may happen that your outgoing connection to the server is slow, and it may timeout not the «execution time» but the «input time», which for example in our system defaulted to 60s. In our case a large upload could take 1 or 2 hours.

Additionally we had «session settings» that should be preserved after upload.

1) You might want review those ini entries:

* session.gc_maxlifetime
* max_input_time
* max_execution_time
* upload_max_filesize
* post_max_size

2) Still fails? Caution, not all are changeable from the script itself. ini_set() might fail to override.

You can see that the «upload_max_filesize», among others, is PHP_INI_PERDIR and not PHP_INI_ALL. This invalidates to use ini_set():
http://www.php.net/manual/en/configuration.changes.modes.php

3) Still fails?. Just make sure you enabled «.htaccess» to overwrite your php settings. This is made in the apache file. You need at least AllowOverride Options.

You will necessarily allow this manually in the case your master files come with AllowOverride None.

Depending on the system, to allow «large file uploads» you must go up and up and up and touch your config necessarily up to the apache config.

These work for me, for 100MB uploads, lasting 2 hours:

In .htaccess:
————————————————————
php_value session.gc_maxlifetime 10800
php_value max_input_time 10800
php_value max_execution_time 10800
php_value upload_max_filesize 110M
php_value post_max_size 120M
————————————————————

In the example,
— As I last 1 to 2 hours, I allow 3 hours (3600×3)
— As I need 100MB, I allow air above for the file (110M) and a bit more for the whole post (120M).

Caution: *DO NOT* trust $_FILES[‘userfile’][‘type’] to verify the uploaded filetype; if you do so your server could be compromised. I’ll show you why below:

The manual (if you scroll above) states: $_FILES[‘userfile’][‘type’] — The mime type of the file, if the browser provided this information. An example would be «image/gif».

Be reminded that this mime type can easily be faked as PHP doesn’t go very far in verifying whether it really is what the end user reported!

So, someone could upload a nasty .php script as an «image/gif» and execute the url to the «image».

My best bet would be for you to check the extension of the file and using exif_imagetype() to check for valid images. Many people have suggested the use of getimagesize() which returns an array if the file is indeed an image and false otherwise, but exif_imagetype() is much faster. (the manual says it so)

Using /var/www/uploads in the example code is just criminal, imnsho.

One should *NOT* upload untrusted files into your web tree, on any server.

Nor should any directory within your web tree have permissions sufficient for an upload to succeed, on a shared server. Any other user on that shared server could write a PHP script to dump anything they want in there!

The $_FILES[‘userfile’][‘type’] is essentially USELESS.
A. Browsers aren’t consistent in their mime-types, so you’ll never catch all the possible combinations of types for any given file format.
B. It can be forged, so it’s crappy security anyway.

One’s code should INSPECT the actual file to see if it looks kosher.

For example, images can quickly and easily be run through imagegetsize and you at least know the first N bytes LOOK like an image. That doesn’t guarantee it’s a valid image, but it makes it much less likely to be a workable security breaching file.

For Un*x based servers, one could use exec and ‘file’ command to see if the Operating System thinks the internal contents seem consistent with the data type you expect.

I’ve had trouble in the past with reading the ‘/tmp’ file in a file upload. It would be nice if PHP let me read that file BEFORE I tried to move_uploaded_file on it, but PHP won’t, presumably under the assumption that I’d be doing something dangerous to read an untrusted file. Fine. One should move the uploaded file to some staging directory. Then you check out its contents as thoroughly as you can. THEN, if it seems kosher, move it into a directory outside your web tree. Any access to that file should be through a PHP script which reads the file. Putting it into your web tree, even with all the checks you can think of, is just too dangerous, imnsho.

There are more than a few User Contributed notes here with naive (bad) advice. Be wary.

Just a quick note that there’s an issue with Apache, the MAX_FILE_SIZE hidden form field, and zlib.output_compression = On. Seems that the browser continues to post up the entire file, even though PHP throws the MAX_FILE_SIZE error properly. Turning zlib compression to OFF seems to solve the issue. Don’t have time to dig in and see who’s at fault, but wanted to save others the hassle of banging their head on this one.

A little codesnippet which returns a filesize in a more legible format.

function display_filesize ( $filesize )

if( is_numeric ( $filesize )) $decr = 1024 ; $step = 0 ;
$prefix = array( ‘Byte’ , ‘KB’ , ‘MB’ , ‘GB’ , ‘TB’ , ‘PB’ );

while(( $filesize / $decr ) > 0.9 ) $filesize = $filesize / $decr ;
$step ++;
>
return round ( $filesize , 2 ). ‘ ‘ . $prefix [ $step ];
> else

Источник

Работа с MIME-типами в PHP

«Internet Media Types» или «Медиа типы» — является стандартом RFC 6838, который описывает формат файла. Причем браузеры используют MIME-типы в качестве основного критерия, не воспринимая расширения файлов.

MIME-тип состоит из типа и подтипа — двух значений разделённых « / », без использования пробелов и в нижнем регистре, например HTML страница:

Полный список MIME типов можно посмотреть тут.

К медиа типу может быть добавлен параметр для указания дополнительных деталей (например кодировка):

Как узнать MIME-тип загруженного файла

При загрузке файла через форму, MIME-тип файла доступен в массиве $_FILES , например:

Для определения MIME уже загруженного файла существует PHP-функция mime_content_type().

echo mime_content_type(__DIR__ . '/image.png'); // image/png echo mime_content_type(__DIR__ . '/text.txt'); // text/plain

При работе с изображениями, MIME-тип можно получить с помощью функции getimagesize():

$filename = __DIR__ . '/image.png'; $info = getimagesize($filename); print_r($info);

Результат:

Array ( [0] => 221 [1] => 96 [2] => 3 [3] => width="221" height="96" [bits] => 8 [mime] => image/png )

Важно помнить что при проверке файлов нельзя полагаться только на проверку MIME, т.к. его значение может быть скомпрометировано. Поэтому нужно проводить более детальную проверку (например по размеру изображения или его пересохранить в предполагаемом формате).

Отправка файлов из PHP

В PHP-скриптах, перед отправкой файлов клиенту, необходимо отправлять заголовок Content-Type , например файл XML:

$content = '. '; header("Content-Type: text/xml; charset=utf-8"); echo $content; exit();
$file = ROOT_DIR . '/market.zip'; header('Content-type: application/zip'); header('Content-Transfer-Encoding: Binary'); header('Content-length: ' . filesize($file)); header('Content-disposition: attachment; filename="' . basename($file) . '"'); readfile($file); exit();

Вывод изображения в зависимости от расширения файла:

$filename = __DIR__ . '/image.png'; $ext = mb_strtolower(mb_substr(mb_strrchr($filename, '.'), 1)); switch ($ext) < case 'png': header('Content-type: image/png'); break; case 'jpg': case 'jpeg': header('Content-type: image/jpeg'); break; case 'gif': header('Content-type: image/gif'); break; case 'wepb': header('Content-type: image/webp'); break; >readfile($filename); exit();

Источник

Оцените статью