- Check disk space php
- PHP FTP Functions
- PHP JASON
- PHP Math Functions
- PHP GMP Functions
- PHP MySQLi Functions
- PHP String Functions
- PHP Network Functions
- PHP IntlChar Functions
- PHP Image Processing and GD Functions
- PHP Gmagick Functions
- PHP Imagick Functions
- PHP ImagickDraw Functions
- PHP DsDeque Functions
- PHP DsMap Functions
- PHP DSSequence Functions
- PHP DSVector Functions
- PHP DsStack Functions
- PHP DsQueue Functions
- PHP DsPriorityQueue Functions
- PHP SPL Data structures
- PHP Basics
- PHP Advance
- PHP Array Functions
- PHP Calendar Functions
- PHP Date/Time Functions
- PHP Directory Functions
- PHP Error
- PHP FTP Functions
- PHP JASON
- PHP Math Functions
- PHP GMP Functions
- PHP MySQLi Functions
- PHP String Functions
- PHP Network Functions
- PHP IntlChar Functions
- PHP Image Processing and GD Functions
- PHP Gmagick Functions
- PHP Imagick Functions
- PHP ImagickDraw Functions
- PHP DsDeque Functions
- PHP DsMap Functions
- PHP DSSequence Functions
- PHP DSVector Functions
- PHP DsStack Functions
- PHP DsQueue Functions
- PHP DsPriorityQueue Functions
- PHP SPL Data structures
- disk_free_space
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 9 notes
- maximal / check-disk-space.php
Check disk space php
- PHP basename( ) Function
- PHP chgrp( ) Function
- PHP chmod( ) Function
- PHP chown( ) Function
- PHP copy( ) Function
- PHP dirname( ) Function
- PHP disk_free_space( ) Function
- PHP disk_total_space( ) Function
- PHP feof( ) Function
- PHP fflush( ) Function
- PHP | fgetc( ) Function
- PHP | fgets( ) Function
- PHP | fgetss( ) Function
- PHP | file_exists( ) Function
- PHP file_get_contents() Function
- PHP Filesystem Functions Complete Reference
PHP FTP Functions
- PHP | ftp_alloc() function
- PHP | ftp_chdir() function
- PHP | ftp_close() function
- PHP | ftp_connect() function
- PHP | ftp_delete() function
- PHP | ftp_exec() function
- PHP | ftp_get() function
- PHP | ftp_put() function
- PHP | ftp_get_option() function
- PHP | ftp_login() function
- PHP | ftp_mdtm() Function
- PHP | ftp_mkdir() function
PHP JASON
PHP Math Functions
PHP GMP Functions
PHP MySQLi Functions
PHP String Functions
PHP Network Functions
PHP IntlChar Functions
PHP Image Processing and GD Functions
PHP Gmagick Functions
PHP Imagick Functions
PHP ImagickDraw Functions
PHP DsDeque Functions
PHP DsMap Functions
- PHP | Ds\Map allocate() Function
- PHP | Ds\Map apply() Function
- PHP | Ds\Map capacity() Function
- PHP | DS\Map clear() Function
- PHP | Ds\Map __construct() Function
- PHP Ds\Map copy() Function
- PHP | Ds\Map count() Function
- PHP | Ds\Map diff() Function
- PHP | Ds\Map filter() Function
- PHP | Ds\Map first() Function
- PHP Ds\Map Functions Complete Reference
PHP DSSequence Functions
PHP DSVector Functions
PHP DsStack Functions
PHP DsQueue Functions
PHP DsPriorityQueue Functions
PHP SPL Data structures
- SplDoublyLinkedList in PHP
- PHP SplDoublyLinkedList add() Function
- PHP SplDoublyLinkedList bottom() Function
- PHP SplDoublyLinkedList count() function
- PHP SplFixedArray count() Function
- PHP SplFixedArray current() Function
- PHP SplFixedArray getSize() Function
- PHP SplFixedArray key() Function
- PHP SplObjectStorage addAll() Function
- PHP SplObjectStorage attach() Function
- PHP SplObjectStorage contains() Function
- PHP SplObjectStorage count() Function
- PHP SplQueue::__construct() Function
- PHP SPL Data structures Complete Reference
PHP Basics
- PHP Tutorial
- PHP | Introduction
- PHP Full Form
- How to set PHP development environment in windows ?
- LAMP installation and important PHP configurations on Ubuntu
- PHP | Coding Standards
- PHP | Basic Syntax
- PHP | Variables
- PHP echo and print
- PHP | Data Types
- PHP | Strings
- PHP | Constants
- PHP | Magic Constants
- PHP | Decision Making
- PHP | Loops
- PHP | Superglobals
- PHP | Regular Expressions
- PHP Examples
PHP Advance
- Describe PHP Include and Require
- PHP | Basics of File Handling
- PHP | fopen( ) (Function open file or URL)
- PHP fread( ) Function
- PHP fclose( ) Function
- PHP | fwrite( ) Function
- PHP | Uploading File
- PHP Cookies
- PHP | Sessions
- PHP Filter and Filter Constant
- Implementing callback in PHP
- Exception Handling in PHP
PHP Array Functions
- PHP | Arrays
- PHP array() Function
- PHP | array_change_key_case() Function
- PHP array_chunk() Function
- PHP | array_column() Function
- PHP array_combine() Function
- PHP array_count_values() Function
- PHP array_diff() function
- PHP array_diff_assoc() Function
- PHP array_diff_key() Function
- PHP array_diff_uassoc() Function
- PHP array_diff_ukey() Function
- PHP array_fill() function
- PHP array_fill_keys() Function
- PHP Array Functions Complete Reference
PHP Calendar Functions
PHP Date/Time Functions
- PHP Date and Time
- PHP | checkdate() Function
- PHP | date_create(), date_format(), date_add() Functions
- PHP | date_create_from_format() Function
- PHP | date_date_set() Function
- PHP | date_default_timezone_get() Function
- PHP | date_default_timezone_set() Function
- PHP | date_diff() Function
- PHP | date_get_last_errors() Function
- PHP | date_isodate_set() Function
- PHP | date_modify() Function
- PHP | date_offset_get() Function
- PHP | date_parse_from_format() Function
- PHP | date_parse() Function
- PHP | date_sub() Function
PHP Directory Functions
PHP Error
- PHP basename( ) Function
- PHP chgrp( ) Function
- PHP chmod( ) Function
- PHP chown( ) Function
- PHP copy( ) Function
- PHP dirname( ) Function
- PHP disk_free_space( ) Function
- PHP disk_total_space( ) Function
- PHP feof( ) Function
- PHP fflush( ) Function
- PHP | fgetc( ) Function
- PHP | fgets( ) Function
- PHP | fgetss( ) Function
- PHP | file_exists( ) Function
- PHP file_get_contents() Function
- PHP Filesystem Functions Complete Reference
PHP FTP Functions
- PHP | ftp_alloc() function
- PHP | ftp_chdir() function
- PHP | ftp_close() function
- PHP | ftp_connect() function
- PHP | ftp_delete() function
- PHP | ftp_exec() function
- PHP | ftp_get() function
- PHP | ftp_put() function
- PHP | ftp_get_option() function
- PHP | ftp_login() function
- PHP | ftp_mdtm() Function
- PHP | ftp_mkdir() function
PHP JASON
PHP Math Functions
PHP GMP Functions
PHP MySQLi Functions
PHP String Functions
PHP Network Functions
PHP IntlChar Functions
PHP Image Processing and GD Functions
PHP Gmagick Functions
PHP Imagick Functions
PHP ImagickDraw Functions
PHP DsDeque Functions
PHP DsMap Functions
- PHP | Ds\Map allocate() Function
- PHP | Ds\Map apply() Function
- PHP | Ds\Map capacity() Function
- PHP | DS\Map clear() Function
- PHP | Ds\Map __construct() Function
- PHP Ds\Map copy() Function
- PHP | Ds\Map count() Function
- PHP | Ds\Map diff() Function
- PHP | Ds\Map filter() Function
- PHP | Ds\Map first() Function
- PHP Ds\Map Functions Complete Reference
PHP DSSequence Functions
PHP DSVector Functions
PHP DsStack Functions
PHP DsQueue Functions
PHP DsPriorityQueue Functions
PHP SPL Data structures
- SplDoublyLinkedList in PHP
- PHP SplDoublyLinkedList add() Function
- PHP SplDoublyLinkedList bottom() Function
- PHP SplDoublyLinkedList count() function
- PHP SplFixedArray count() Function
- PHP SplFixedArray current() Function
- PHP SplFixedArray getSize() Function
- PHP SplFixedArray key() Function
- PHP SplObjectStorage addAll() Function
- PHP SplObjectStorage attach() Function
- PHP SplObjectStorage contains() Function
- PHP SplObjectStorage count() Function
- PHP SplQueue::__construct() Function
- PHP SPL Data structures Complete Reference
disk_free_space
Функция возвращает размер свободного пространства в байтах, доступного для использования в указанном каталоге или файловой системе.
Список параметров
Директория или раздел диска.
Замечание:
Если вместо директории будет передано имя файла, то поведение данной функции неизвестно и может отличаться на разных операционных системах и версиях PHP.
Возвращаемые значения
Возвращает количество свободных байт в виде числа с плавающей точкой или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования функции disk_free_space()
// $df содержит размер свободного места в каталоге «/»
$df = disk_free_space ( «/» );
?php
// В Windows:
$df_c = disk_free_space ( «C:» );
$df_d = disk_free_space ( «D:» );
?>
Примечания
Замечание: Эта функция неприменима для работы с удалёнными файлами, поскольку файл должен быть доступен через файловую систему сервера.
Смотрите также
User Contributed Notes 9 notes
Transformation is possible WITHOUT using loops:
$bytes = disk_free_space ( «.» );
$si_prefix = array( ‘B’ , ‘KB’ , ‘MB’ , ‘GB’ , ‘TB’ , ‘EB’ , ‘ZB’ , ‘YB’ );
$base = 1024 ;
$class = min ((int) log ( $bytes , $base ) , count ( $si_prefix ) — 1 );
echo $bytes . ‘
‘ ;
echo sprintf ( ‘%1.2f’ , $bytes / pow ( $base , $class )) . ‘ ‘ . $si_prefix [ $class ] . ‘
‘ ;
?>
$si_prefix = array( ‘B’, ‘KB’, ‘MB’, ‘GB’, ‘TB’, ‘EB’, ‘ZB’, ‘YB’ );
you are missing the petabyte after terabyte
‘B’, ‘KB’, ‘MB’, ‘GB’, ‘TB’, ‘PB’, ‘EB’, ‘ZB’, ‘YB’
Nice, but please be aware of the prefixes.
SI specifies a lower case ‘k’ as 1’000 prefix.
It doesn’t make sense to use an upper case ‘K’ as binary prefix,
while the decimal Mega (M and following) prefixes in SI are uppercase.
Furthermore, there are REAL binary prefixes since a few years.
Do it the (newest and recommended) «IEC» way:
KB’s are calculated decimal; power of 10 (1000 bytes each)
KiB’s are calculated binary; power of 2 (1024 bytes each).
The same goes for MB, MiB and so on.
Another easy way to convert bytes to human readable sizes would be this:
function HumanSize ( $Bytes )
$Type =array( «» , «kilo» , «mega» , «giga» , «tera» , «peta» , «exa» , «zetta» , «yotta» );
$Index = 0 ;
while( $Bytes >= 1024 )
$Bytes /= 1024 ;
$Index ++;
>
return( «» . $Bytes . » » . $Type [ $Index ]. «bytes» );
>
?>
It simply takes the $Bytes and divides it by 1024 bytes untill it’s no longer over or equal to 1024, meanwhile it increases the $Index to allocate which suffix belongs to the return (adding ‘bytes’ to the end to save some space).
You can easily modify it so it’s shorter, but I made it so it’s more clearer.
This is not documented yet.
If $directory is invalid, then disk_free_space() will return false and ALSO throw a Warning: «disk_free_space(): No such file or directory»
With respect to Linux filesystems, I’ll point out that this function returns the space available in the current volume or mountpoint, not the total physical disk space. That is, this function used on the ‘/root’ volume shows the free space in /root, which is different from ‘/home’, and so on.
On Windows, this also works with distant files, by using their full network path.
For instance, this will give the % of free disk space on the share «dir» from remote host «server» :
$path = «\\\\server\\dir» ;
echo( floor ( 100 * disk_free_space ( $disk ) / disk_total_space ( $disk )));
?>
It can also work with drive letters mapped to a network path in certain cases.
function size ( $size , array $options = null )
$o = [
‘binary’ => false ,
‘decimalPlaces’ => 2 ,
‘decimalSeparator’ => ‘.’ ,
‘thausandsSeparator’ => » ,
‘maxThreshold’ => false , // or thresholds key
‘sufix’ => [
‘thresholds’ => [ » , ‘K’ , ‘M’ , ‘G’ , ‘T’ , ‘P’ , ‘E’ , ‘Z’ , ‘Y’ ],
‘decimal’ => ‘ B’ ,
‘binary’ => ‘ iB’
]
];
if ( $options !== null )
$o = array_replace_recursive ( $o , $options );
$count = count ( $o [ ‘sufix’ ][ ‘thresholds’ ]);
$pow = $o [ ‘binary’ ] ? 1024 : 1000 ;
if (( $size < pow ( $pow , $i + 1 )) ||
( $i === $o [ ‘maxThreshold’ ]) ||
( $i === ( $count — 1 ))
)
return
number_format (
$size / pow ( $pow , $i ),
$o [ ‘decimalPlaces’ ],
$o [ ‘decimalSeparator’ ],
$o [ ‘thausandsSeparator’ ]
) .
str_replace (
» ,
$o [ ‘sufix’ ][ ‘thresholds’ ][ $i ],
$o [ ‘sufix’ ][ $o [ ‘binary’ ] ? ‘binary’ : ‘decimal’ ]
);
>
var_dump ( size ( disk_free_space ( ‘/’ )));
// string(8) «14.63 GB»
var_dump ( size ( disk_free_space ( ‘/’ ), [ ‘binary’ => true ]));
// string(9) «13.63 GiB»
var_dump ( size ( disk_free_space ( ‘/’ ), [ ‘maxThreshold’ => 2 ]));
// string(11) «14631.90 MB»
var_dump ( size ( disk_free_space ( ‘/’ ), [ ‘binary’ => true , ‘maxThreshold’ => 2 ]));
// string(12) «13954.07 MiB»
maximal / check-disk-space.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* Скрипт для проверки свободного места на диске. |
* |
* Запуск в кроне (каждый день в 7 утра): |
* «` |
* 0 7 * * * php /path/to/check-disk-space.php |
* «` |
* |
* @author MaximAL |
* @date 2019-11-26 |
* @time 11:43 |
* @since 2019-11-26 Первая версия. |
* |
* @copyright © MaximAL, Sijeko 2019 |
* @link https://maximals.ru |
* @link https://sijeko.ru |
*/ |
// Разделы, которые проверяем |
$ partitions = [ |
‘/’ , |
‘/home’ , |
‘/srv’ , |
‘/run’ , |
]; |
// Порог, меньше которого шлём уведомление |
$ gbMin = 5 ; |
// Выводить ли сообщение в консоль (чтобы его отослал cron с использованием MAILTO) |
$ textOut = true ; |
// Отправлять ли сообщение самостоятельно (функцией `mail()`) |
$ mailSend = true ; |
// Получатели письма |
$ mailTo = ‘admin@example.org, maximal@example.org’ ; |
// Тема письма (добавляем к нему имя сервера) |
$ mailSubject = ‘[‘ . gethostname() . ‘] Мало места на диске’ ; |
// Начальный текст письма |
$ mailHeader = |
‘В этих разделах сервера `’ . gethostname() . |
‘` осталось меньше ‘ . $ gbMin . ‘ ГиБ свободного места:’ ; |
// Поехали! |
$ timeStart = microtime( true ); |
$ alerts = []; |
foreach ( $ partitions as $ partition ) |
$ gBytes = disk_free_space( $ partition ) / 1024.0 / 1024.0 / 1024.0 ; |
if ( $ gBytes < $ gbMin ) |
$ alerts []= ‘* ‘ . $ partition . ‘: ‘ . round( $ gBytes , 1 ) . ‘ ГиБ’ ; |
> |
> |
if (count( $ alerts )) |
$ message = $ mailHeader . PHP_EOL . implode( PHP_EOL , $ alerts ) . PHP_EOL ; |
if ( $ mailSend ) |
mail( $ mailTo , $ mailSubject , $ message ); |
> |
if ( $ textOut ) |
echo $ message ; |
> |
> |
$ timeDiff = microtime( true ) — $ timeStart ; |
//echo ‘Time: ‘, sprintf(‘%.3f sec.’, $timeDiff), PHP_EOL; |