Php files filename size

PHP: Get file size.

This is a guide on how to get the size of a file using PHP. In this tutorial, we will get the size of a file in bytes using PHP’s filesize function before converting those bytes into KB, MB and GB, which are far more human-friendly.

PHP’s filesize function.

PHP’s filesize function takes in one parameter: A string parameter called $filename, which should contain the path to the file.

Take a look at the following example:

//The path to our file. $file = 'photograph.jpg'; //Get the file size in bytes using PHP's filesize function. $fileSizeBytes = filesize($file); //In my case, the file was 269,708 bytes in size. var_dump($fileSizeBytes);

The code snippet above assumes that the file “photograph.jpg” is located in the same directory as our PHP script.

If our file was located in another directory called images, we could use the following relative path:

//A relative path. $file = '../images/photograph.jpg'; //Get the file size in bytes. $fileSizeBytes = filesize($file);

Note that the filesize function will also accept an absolute path to the file:

//Using an absolute path. $file = 'C:\wamp\www\photograph.jpg'; //Get the file size in bytes. $fileSizeBytes = filesize($file);

If the filesize function is given an incorrect file path, it will throw the following warning:

“Warning: filesize(): stat failed for /path/to/photograph.jpg”

PHP’s filesize function uses the system’s underlying stat command to get the size of the file in question.

Getting the file size in KB.

If you are primarily dealing with images or other small files, you might want to convert the bytes into KB (kilobytes).

//Relative path to our file. $file = 'photograph.jpg'; //Get the file size in bytes. $fileSizeBytes = filesize($file); //Convert the bytes into KB. $fileSizeKB = round($fileSizeBytes / 1024); //269,708 bytes divided by 1024 results in 263 KB var_dump($fileSizeKB);

In the code snippet above, we got the size of the file in bytes and then divided the result by 1024. This is because there are roughly 1024 bytes in every kilobyte.

Читайте также:  Install python virtualenv debian

Getting the file size in MB.

The MB (megabyte) is a useful metric if you are dealing with MP3 files, Zip Files, PDFs or other relatively-large files.

An example of getting a file’s size in MB:

//Path to our file. $file = 'photograph.jpg'; //Get the file size in bytes. $fileSizeBytes = filesize($file); //Convert the bytes into MB. $fileSizeMB = ($fileSizeBytes / 1024 / 1024); //269,708 bytes is 0.2572135925293 MB var_dump($fileSizeMB); //Format it so that only 2 decimal points are displayed. $fileSizeMB = number_format($fileSizeMB, 2); //It now becomes 0.26 MB. var_dump($fileSizeMB);
  1. Got the size of the file in bytes using PHP’s filesize function.
  2. Converted the bytes into MB by dividing the bytes by 1024 twice.
  3. Because the result contains far two many decimal places, we used PHP’s number_format function to limit the number of decimal places to 2.

In my case, the “photograph.jpg” file was 269,708 bytes in size, which became 0.26 MB.

Using PHP to get the file size in GB.

If you are dealing with large files such as videos, you might want to use GB (gigabytes):

//The path to our file. $file = 'large-file.mp4'; //Get the file size in bytes. $fileSizeBytes = filesize($file); //Convert the bytes into GB. $fileSizeGB = ($fileSizeBytes / 1024 / 1024 / 1024); var_dump($fileSizeGB);

In the code sample above, we converted the bytes into GB by dividing the result of filesize by 1024 three times.

filesize won’t work with remote files.

The filesize function will not work with remote files. If you attempt to get the size of a remote file using the filesize function, it will spit out the following warning:

Warning: filesize(): stat failed for http://example.com/file.mp4

This is because the underlying stat command does not support remote files. See: Get the size of a remote file using PHP.

Читайте также:  Php отключить warning notice

Источник

Массив $_FILES

В PHP-скрипте обработка загруженных через форму происходит через глобальный массив $_FILES , рассмотрим его содержимое:

Загрузка одного файла

Чтобы форма отправила файл, необходимо использовать только метод POST для отправки данных и добавить к тегу атрибут enctype=»multipart/form-data» , который определяет способ кодирования данных формы при их отправке на сервер.

Код скрипта index.php:

Результат:

Array( [name] => image.jpg [type] => image/jpeg [tmp_name] => /home/user/temp/phpjX2YXo [error] => 0 [size] => 119303 )

Описание значений массива $_FILES :

$_FILES[‘file-1’][‘name’] Оригинальное имя файла на компьютере клиента.
$_FILES[‘file-1’][‘type’] Mime-тип файла, в случае, если браузер предоставил такую информацию. Этот mime-тип не проверяется на стороне PHP, так что не полагайтесь на его значение без проверки.
$_FILES[‘file-1’][‘size’] Размер принятого файла в байтах .
$_FILES[‘file-1’][‘tmp_name’] Временное имя, с которым принятый файл был сохранен на сервере.
$_FILES[‘file-1’][‘error’] Код ошибки, которая может возникнуть при загрузке файла.

Загрузка несколько файлов

Для загрузки сразу нескольких файлов к нужно добавить атрибут multiple , а к имени поля – [] .

Код скрипта index.php

Результат:

Array( [name] => Array( [0] => image.jpg [1] => arhive.zip ) [type] => Array( [0] => image/jpeg [1] => application/zip ) [tmp_name] => Array( [0] => /home/user/temp/phpK3h32F [1] => /home/user/temp/phpBrGxus ) [error] => Array( [0] => 0 [1] => 0 ) [size] => Array( [0] => 119303 [1] => 6792 ) )

Как видно, структура массива разделена по свойствам, а не по файлам. Для удобства работы с циклом foreach массив $_FILES можно преобразовать:

 $l) < foreach($l as $i =>$v) < $files[$i][$k] = $v; >> $_FILES['file-2'] = $files; print_r($_FILES);

Результат:

Array( [0] => Array( [name] => image.jpg [type] => image/jpeg [tmp_name] => /home/user/temp/phpKgSQbo [error] => 0 [size] => 119303 ) [1] => Array( [name] => arhive.zip [type] => application/zip [tmp_name] => /home/user/temp/phpVht8LS [error] => 0 [size] => 6792 ) )

Максимальный размер загружаемого файла

Размер загружаемого файла можно ограничить, добавив в форму скрытое поле с максимальным размером файла :

Читайте также:  Html fixed width font

В случае превышения размера файла в переменной $_FILES[‘file-1’][‘error’] будет ошибка с кодом « 2 ».

Коды ошибок загрузки файлов

В случаи, если при загрузке файла произошла ошибка, в переменной $_FILES[‘file’][‘error’] будет содержатся её код. Возможны следующие значения:

Код Константа Описание
0 UPLOAD_ERR_OK Ошибок не возникло, файл успешно загружен на сервер.
1 UPLOAD_ERR_INI_SIZE Размер файла превысил максимально допустимый размер, который задан директивой upload_max_filesize
2 UPLOAD_ERR_FORM_SIZE Размер загружаемого файла превысил значение MAX_FILE_SIZE, указанное в HTML-форме.
3 UPLOAD_ERR_PARTIAL Загружаемый файл был получен только частично.
4 UPLOAD_ERR_NO_FILE Файл не был загружен.
6 UPLOAD_ERR_NO_TMP_DIR Отсутствует временная папка.
7 UPLOAD_ERR_CANT_WRITE Не удалось записать файл на диск (возникает, когда на хостинге закончилось место).
8 UPLOAD_ERR_EXTENSION PHP-расширение остановило загрузку файла.

Настройки PHP

Обычно настройки загрузки файлов на хостинге вполне нормальные и не вызывают проблем, но есть исключения. Если не загружаются большие файлы, то скорее всего установлен лимит на размер загружаемого файла, ограничено время загрузки файла или ограничено количество одновременных загрузок.

Посмотреть установленные значения можно с помощью функции phpinfo() , в разделе «Core».

Раздел «Core» в phpinfo

В php.ini:

; Разрешение на загрузку файлов file_uploads = On ; Максимальное время выполнения скрипта в секундах max_execution_time = 60 ; Максимальное потребление памяти одним скриптом memory_limit = 64M ; Максимально допустимый размер данных отправляемых методом POST post_max_size = 50M ; Папка для хранения файлов во время загрузки upload_tmp_dir = home/user/temp ; Максимальный размер загружаемого файла upload_max_filesize = 5M ; Максимально разрешённое количество одновременно загружаемых файлов max_file_uploads = 10

В .htaccess:

# Разрешение на загрузку файлов php_value file_uploads On # Максимальное время выполнения скрипта в секундах php_value max_execution_time 60 # Максимальное потребление памяти одним скриптом php_value memory_limit 64M # Максимально допустимый размер данных отправляемых методом POST php_value post_max_size 50M # Папка для хранения файлов во время загрузки php_value upload_tmp_dir home/user/temp # Максимальный размер загружаемого файла php_value upload_max_filesize 5M # Максимально разрешённое количество одновременно загружаемых файлов php_value max_file_uploads 10

Источник

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