Смотрите также
За описанием сопутствующих функций, таких как dirname() , is_dir() , mkdir() и rmdir() , обратитесь к главе Файловая система.
User Contributed Notes 7 notes
17 years ago
I wrote a simple backup script which puts all files in his folder (and all of the sub-folders) in one TAR archive.
(It’s classic TAR format not USTAR, so filename and path to it can’t be longer then 99 chars)
/***********************************************************
* Title: Classic-TAR based backup script v0.0.1-dev
**********************************************************/
Class Tar_by_Vladson var $tar_file ;
var $fp ;
function Tar_by_Vladson ( $tar_file = ‘backup.tar’ ) $this -> tar_file = $tar_file ;
$this -> fp = fopen ( $this -> tar_file , «wb» );
$tree = $this -> build_tree ();
$this -> process_tree ( $tree );
fputs ( $this -> fp , pack ( «a512» , «» ));
fclose ( $this -> fp );
>
function build_tree ( $dir = ‘.’ ) $handle = opendir ( $dir );
while( false !== ( $readdir = readdir ( $handle ))) if( $readdir != ‘.’ && $readdir != ‘..’ ) $path = $dir . ‘/’ . $readdir ;
if ( is_file ( $path )) $output [] = substr ( $path , 2 , strlen ( $path ));
> elseif ( is_dir ( $path )) $output [] = substr ( $path , 2 , strlen ( $path )). ‘/’ ;
$output = array_merge ( $output , $this -> build_tree ( $path ));
>
>
>
closedir ( $handle );
return $output ;
>
function process_tree ( $tree ) foreach( $tree as $pathfile ) if ( substr ( $pathfile , — 1 , 1 ) == ‘/’ ) fputs ( $this -> fp , $this -> build_header ( $pathfile ));
> elseif ( $pathfile != $this -> tar_file ) $filesize = filesize ( $pathfile );
$block_len = 512 * ceil ( $filesize / 512 )- $filesize ;
fputs ( $this -> fp , $this -> build_header ( $pathfile ));
fputs ( $this -> fp , file_get_contents ( $pathfile ));
fputs ( $this -> fp , pack ( «a» . $block_len , «» ));
>
>
return true ;
>
function build_header ( $pathfile ) if ( strlen ( $pathfile ) > 99 ) die( ‘Error’ );
$info = stat ( $pathfile );
if ( is_dir ( $pathfile ) ) $info [ 7 ] = 0 ;
$header = pack ( «a100a8a8a8a12A12a8a1a100a255» ,
$pathfile ,
sprintf ( «%6s » , decoct ( $info [ 2 ])),
sprintf ( «%6s » , decoct ( $info [ 4 ])),
sprintf ( «%6s » , decoct ( $info [ 5 ])),
sprintf ( «%11s » , decoct ( $info [ 7 ])),
sprintf ( «%11s» , decoct ( $info [ 9 ])),
sprintf ( «%8s» , » » ),
( is_dir ( $pathfile ) ? «5» : «0» ),
«» ,
«»
);
clearstatcache ();
$checksum = 0 ;
for ( $i = 0 ; $i < 512 ; $i ++) $checksum += ord ( substr ( $header , $i , 1 ));
>
$checksum_data = pack (
«a8» , sprintf ( «%6s » , decoct ( $checksum ))
);
for ( $i = 0 , $j = 148 ; $i < 7 ; $i ++, $j ++)
$header [ $j ] = $checksum_data [ $i ];
return $header ;
>
>
header ( ‘Content-type: text/plain’ );
$start_time = array_sum ( explode ( chr ( 32 ), microtime ()));
$tar = & new Tar_by_Vladson ();
$finish_time = array_sum ( explode ( chr ( 32 ), microtime ()));
printf ( «The time taken: %f seconds» , ( $finish_time — $start_time ));
?>
17 years ago
Here is a very similar function to *scandir*, if you are still using PHP4.
This recursive function will return an indexed array containing all directories or files or both (depending on parameters). You can specify the depth you want, as explained below.
// $path : path to browse
// $maxdepth : how deep to browse (-1=unlimited)
// $mode : «FULL»|»DIRS»|»FILES»
// $d : must not be defined
function searchdir ( $path , $maxdepth = — 1 , $mode = «FULL» , $d = 0 )
if ( substr ( $path , strlen ( $path ) — 1 ) != ‘/’ ) < $path .= '/' ; >
$dirlist = array () ;
if ( $mode != «FILES» ) < $dirlist [] = $path ; >
if ( $handle = opendir ( $path ) )
while ( false !== ( $file = readdir ( $handle ) ) )
if ( $file != ‘.’ && $file != ‘..’ )
$file = $path . $file ;
if ( ! is_dir ( $file ) ) < if ( $mode != "DIRS" ) < $dirlist [] = $file ; >>
elseif ( $d >= 0 && ( $d < $maxdepth || $maxdepth < 0 ) )
$result = searchdir ( $file . ‘/’ , $maxdepth , $mode , $d + 1 ) ;
$dirlist = array_merge ( $dirlist , $result ) ;
>
>
>
closedir ( $handle ) ;
>
if ( $d == 0 ) < natcasesort ( $dirlist ) ; >
return ( $dirlist ) ;
>
17 years ago
I would like to present these two simple functions for generating a complete directory listing — as I feel the other examples are to restrictive in terms of usage.
Usage is as simple as this:
$dir = «»;
$arDirTree = dirTree($dir);
printTree($arDirTree);
It is easy to add files to the tree also — so enjoy.
17 years ago
To join directory and file names in a cross-platform manner you can use the following function.
function join_path()
$num_args = func_num_args();
$args = func_get_args();
$path = $args[0];
It should do the following:
$src = join_path( ‘/foo’, ‘bar’, ‘john.jpg’ );
echo $src; // On *nix -> /foo/bar/john.jpg
$src = join_path( ‘C:\www’, ‘domain.com’, ‘foo.jpg’ );
echo $src; // On win32 -> C:\\www\\domain.com\\foo.jpg
16 years ago
Samba mounts under a Windows environment are not accessible using the mounted drive letter. For instance, if you have drive X: in Windows mounted to //example.local/shared_dir (where example.local is a *nix box running Samba), the following constructs
$dir = «X:\\data\\»;
$handle = opendir( $dir );
or
$d = dir( $dir );
will return a warning message «failed to open dir: No error»
On the other hand, using the underlying mapping info works just fine. For example:
$dir = «//example.local/shared_dir/data»;
$handle = opendir( $dir );
or
$d = dir( $dir );
Both cases do what they’re expected to.
16 years ago
Mine works as long as the samba volume is actually mounted. Having it listed in the «My Computer» window doesn’t warrant that.
16 years ago
I have posted this same observation in scandir, and found out that it is not limited to scandir alone but to ALL directory functions.
Directory functions DOES NOT currently supports Japanese characters.
- Каталоги
- Установка и настройка
- Предопределённые константы
- Directory
- Функции для работы с каталогами
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
copy
Если вы хотите переименовать файл, используйте функцию rename() .
Список параметров
Путь к исходному файлу.
Путь к целевому файлу. Если to является URL, то операция копирования может завершиться ошибкой, если обёртка URL не поддерживает перезаписывание существующих файлов.
Внимание
Если целевой файл уже существует, то он будет перезаписан.
Корректный ресурс контекста, созданный функцией stream_context_create() .
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования функции copy()
$file = ‘example.txt’ ;
$newfile = ‘example.txt.bak’ ;?php
if (! copy ( $file , $newfile )) echo «не удалось скопировать $file . \n» ;
>
?>Смотрите также
- move_uploaded_file() — Перемещает загруженный файл в новое место
- rename() — Переименовывает файл или директорию
- Раздел руководства «Загрузка файлов»
User Contributed Notes 24 notes
19 years ago
Having spent hours tacking down a copy() error: Permission denied , (and duly worrying about chmod on winXP) , its worth pointing out that the ‘destination’ needs to contain the actual file name ! — NOT just the path to the folder you wish to copy into.
DOH !
hope this saves somebody hours of fruitless debugging17 years ago
It take me a long time to find out what the problem is when i’ve got an error on copy(). It DOESN’T create any directories. It only copies to existing path. So create directories before. Hope i’ll help,
15 years ago
Don’t forget; you can use copy on remote files, rather than doing messy fopen stuff. e.g.
if(!@ copy ( ‘http://someserver.com/somefile.zip’ , ‘./somefile.zip’ ))
$errors = error_get_last ();
echo «COPY ERROR: » . $errors [ ‘type’ ];
echo «
\n» . $errors [ ‘message’ ];
> else echo «File copied from remote!» ;
>
?>2 years ago
On Windows, php-7.4.19-Win32-vc15-x64 — copy() corrupted a 6GB zip file. Our only recourse was to write:
function file_win_copy( $src, $dst ) shell_exec( ‘COPY «‘.$src.'» «‘.$dst.'»‘);
return file_exists($dest);
>12 years ago
Here is a simple script that I use for removing and copying non-empty directories. Very useful when you are not sure what is the type of a file.
I am using these for managing folders and zip archives for my website plugins.
// removes files and non-empty directories
function rrmdir ( $dir ) if ( is_dir ( $dir )) $files = scandir ( $dir );
foreach ( $files as $file )
if ( $file != «.» && $file != «..» ) rrmdir ( » $dir / $file » );
rmdir ( $dir );
>
else if ( file_exists ( $dir )) unlink ( $dir );
>// copies files and non-empty directories
function rcopy ( $src , $dst ) if ( file_exists ( $dst )) rrmdir ( $dst );
if ( is_dir ( $src )) mkdir ( $dst );
$files = scandir ( $src );
foreach ( $files as $file )
if ( $file != «.» && $file != «..» ) rcopy ( » $src / $file » , » $dst / $file » );
>
else if ( file_exists ( $src )) copy ( $src , $dst );
>
?>Cheers!
10 years ago
A nice simple trick if you need to make sure the folder exists first:
$srcfile = ‘C:\File\Whatever\Path\Joe.txt’ ;
$dstfile = ‘G:\Shared\Reports\Joe.txt’ ;
mkdir ( dirname ( $dstfile ), 0777 , true );
copy ( $srcfile , $dstfile );9 years ago
Below a code snippet for downloading a file from a web server to a local file.
It demonstrates useful customizations of the request (such as setting a User-Agent and Referrer, often required by web sites), and how to download only files if the copy on the web site is newer than the local copy.
It further demonstrates the processing of response headers (if set by server) to determine the timestamp and file name. The file type is checked because some servers return a 200 OK return code with a textual «not found» page, instead of a proper 404 return code.
// $fURI: URL to a file located on a web server
// $target_file: Path to a local fileif ( file_exists ( $target_file ) ) $ifmodhdr = ‘If-Modified-Since: ‘ . date ( «r» , filemtime ( $target_file ) ). «\r\n» ;
>
else $ifmodhdr = » ;
>// set request header for GET with referrer for modified files, that follows redirects
$arrRequestHeaders = array(
‘http’ =>array(
‘method’ => ‘GET’ ,
‘protocol_version’ => 1.1 ,
‘follow_location’ => 1 ,
‘header’ => «User-Agent: Anamera-Feed/1.0\r\n» .
«Referer: $source \r\n» .
$ifmodhdr
)
);
$rc = copy ( $fURI , $target_file , stream_context_create ( $arrRequestHeaders ) );// HTTP request completed, preserve system error, if any
if( $rc ) if ( fclose ( $rc ) ) unset( $err );
>
else $err = error_get_last ();
>
>
else $err = error_get_last ();
>// Parse HTTP Response Headers for HTTP Status, as well filename, type, date information
// Need to start from rear, to get last set of headers after possible sets of redirection headers
if ( $http_response_header ) for ( $i = sizeof ( $http_response_header ) — 1 ; $i >= 0 ; $i — ) if ( preg_match ( ‘@^http/\S+ (\S) (.+)$@i’ , $http_response_header [ $i ], $http_status ) > 0 ) // HTTP Status header means we have reached beginning of response headers for last request
break;
>
elseif ( preg_match ( ‘@^(\S+):\s*(.+)\s*$@’ , $http_response_header [ $i ], $arrHeader ) > 0 ) switch ( $arrHeader [ 1 ] ) case ‘Last-Modified’ :
if ( !isset( $http_content_modtime ) ) $http_content_modtime = strtotime ( $arrHeader [ 2 ] );
>
break;
case ‘Content-Type’ :
if ( !isset( $http_content_image_type ) ) if ( preg_match ( ‘@^image/(\w+)@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) if ( in_array ( strtolower ( $arrTokens [ 1 ]), $arrValidTypes )) $http_content_image_type = $arrTokens [ 1 ];
break;
>
>
throw new Exception ( «Error accessing file $fURI ; invalid content type: $arrHeader [ 2 ] » , 2 );
>
break;
case ‘Content-Disposition’ :
if ( !isset( $http_content_filename ) && preg_match ( ‘@filename\\s*=\\s*(?|»([^»]+)»|([\\S]+));?@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) $http_content_filename = basename ( $arrTokens [ 1 ]);
>
break;
>
>
>
>if ( $http_status ) // Make sure we have good HTTP Status
switch ( $http_status [ 1 ] ) case ‘200’ :
// SUCCESS: HTTP Status is «200 OK»
break;
case ‘304’ :
throw new Exception ( «Remote file not newer: $fURI » , $http_status [ 1 ] );
break;
case ‘404’ :
throw new Exception ( «Remote file not found: $fURI » , $http_status [ 1 ] );
break;
default:
throw new Exception ( «HTTP Error, $http_status [ 2 ] , accessing $fURI » , $http_status [ 1 ] );
break;
>
>
elseif ( $err ) // Protocol / Communication error
throw new Exception ( $err [ ‘message’ ] /*.»; Remote file: $fURI»*/ , $err [ ‘type’ ] );
>
else // No HTTP status and no error
throw new customException ( «Unknown HTTP response accessing $fURI : $http_response_header [ 0 ] » , — 1 );
>
?>Notes:
1. Currently copy() does NOT appropriately handle the 304 response code. Instead of NOT performing a copy (possibly setting the RC), it will overwrite the target file with an zero length file.
2. There may be a problem accessing a list of remote files when HTTP 1.1 protocol is used. If you experience time-out errors, try the default 1.0 protocol version.How to read a list of files from a folder using PHP? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago .
I want to read a list the names of files in a folder in a web page using php. is there any simple script to acheive it?
asked Apr 6, 2009 at 9:18
Arun Annamalai Arun Annamalai
795 1 1 gold badge 7 7 silver badges 20 20 bronze badges9 Answers 9
The simplest and most fun way (imo) is glob
foreach (glob("*.*") as $filename) < echo $filename."
"; >But the standard way is to use the directory functions.
if (is_dir($dir)) < if ($dh = opendir($dir)) < while (($file = readdir($dh)) !== false) < echo "filename: .".$file."
"; > closedir($dh); > >There are also the SPL DirectoryIterator methods. If you are interested
53k 45 45 gold badges 177 177 silver badges 245 245 bronze badges
answered Apr 6, 2009 at 9:20
Ólafur Waage Ólafur Waage
69k 22 22 gold badges 143 143 silver badges 199 199 bronze badgesI don’t recommend Glob — ever! It is extremely slow especially with many files. I would use one of these: FilesystemIterator, DirectoryIterator, RecursiveDirectoryIterator.
Apr 10, 2017 at 15:44
$dir = getcwd(); gets the current working directory.
Sep 20, 2018 at 7:25
What’s the purpose of !== false ?
Feb 18, 2019 at 21:25This is what I like to do:
$files = array_values(array_filter(scandir($path), function($file) use ($path) < return !is_dir($path . '/' . $file); >)); foreach($files as $file)
5,510 56 56 silver badges 53 53 bronze badges
answered Oct 29, 2014 at 13:57
Bruno Calza Bruno Calza
2,752 2 2 gold badges 23 23 silver badges 25 25 bronze badges
Needs one small fix: function($file) use ($path) < return !is_dir($path . '/' . $file); Jun 28, 2017 at 15:54There is this function scandir():
$dir = 'dir'; $files = scandir($dir, 0); for($i = 2; $i < count($files); $i++) print $files[$i]."
";answered Oct 29, 2014 at 13:04
161 1 1 silver badge 2 2 bronze badgesIf you have problems with accessing to the path, maybe you need to put this:
$root = $_SERVER['DOCUMENT_ROOT']; $path = "/cv/"; // Open the folder $dir_handle = @opendir($root . $path) or die("Unable to open $path");answered Apr 29, 2013 at 18:37
1,617 19 19 silver badges 16 16 bronze badgesThere is a glob. In this webpage there are good article how to list files in very simple way:
answered Aug 4, 2013 at 15:34
41 1 1 bronze badgeNote that link-only answers are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference.
Aug 4, 2013 at 15:52
You can use standard directory functions
$dir = opendir('/tmp'); while ($file = readdir($dir)) < if ($file == '.' || $file == '..') < continue; >echo $file; > closedir($dir);filesize
Возвращает размер указанного файла в байтах или false (и генерирует ошибку уровня E_WARNING ) в случае возникновения ошибки.
Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Примеры
Пример #1 Пример использования функции filesize()
// Пример вывода: Размер файла somefile.txt: 1024 байтов
$filename = ‘somefile.txt’ ;
echo ‘Размер файла ‘ . $filename . ‘: ‘ . filesize ( $filename ) . ‘ байтов’ ;Примечания
Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .
Подсказка
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.
Смотрите также
- file_exists() — Проверяет существование указанного файла или каталога
User Contributed Notes 36 notes
12 years ago
Extremely simple function to get human filesize.
function human_filesize ( $bytes , $decimals = 2 ) $sz = ‘BKMGTP’ ;
$factor = floor (( strlen ( $bytes ) — 1 ) / 3 );
return sprintf ( «%. < $decimals >f» , $bytes / pow ( 1024 , $factor )) . @ $sz [ $factor ];
>
?>12 years ago
if you recently appended something to file, and closed it then this method will not show appended data:
// get contents of a file into a string
$filename = «/usr/local/something.txt» ;
$handle = fopen ( $filename , «r» );
$contents = fread ( $handle , filesize ( $filename ));
fclose ( $handle );
?>
You should insert a call to clearstatcache() before calling filesize()
I’ve spent two hours to find that =/6 years ago
// Recover all file sizes larger than > 4GB.
// Works on php 32bits and 64bits and supports linux
// Used the com_dotnet extensionfunction getSize ( $file ) $size = filesize ( $file );
if ( $size if (!( strtoupper ( substr ( PHP_OS , 0 , 3 )) == ‘WIN’ )) $size = trim (` stat -c%s $file `);
>
else $fsobj = new COM ( «Scripting.FileSystemObject» );
$f = $fsobj -> GetFile ( $file );
$size = $f -> Size ;
>
return $size ;
>
?>10 years ago
/**
* Converts bytes into human readable file size.
*
* @param string $bytes
* @return string human readable file size (2,87 Мб)
* @author Mogilev Arseny
*/
function FileSizeConvert ( $bytes )
$bytes = floatval ( $bytes );
$arBytes = array(
0 => array(
«UNIT» => «TB» ,
«VALUE» => pow ( 1024 , 4 )
),
1 => array(
«UNIT» => «GB» ,
«VALUE» => pow ( 1024 , 3 )
),
2 => array(
«UNIT» => «MB» ,
«VALUE» => pow ( 1024 , 2 )
),
3 => array(
«UNIT» => «KB» ,
«VALUE» => 1024
),
4 => array(
«UNIT» => «B» ,
«VALUE» => 1
),
);?php
foreach( $arBytes as $arItem )
if( $bytes >= $arItem [ «VALUE» ])
$result = $bytes / $arItem [ «VALUE» ];
$result = str_replace ( «.» , «,» , strval ( round ( $result , 2 ))). » » . $arItem [ «UNIT» ];
break;
>
>
return $result ;
>18 years ago
This function quickly calculates the size of a directory:
http://aidanlister.com/repos/v/function.dirsize.phpFor a faster (unix only) implementation, see function.disk-total-space, note #34100
http://www.php.net/manual/en/function.disk-total-space.php#34100Also of interest is this wikipedia article, discussing the difference between a kilobyte (1000) and a kibibyte (1024).
http://en.wikipedia.org/wiki/Bytes6 years ago
This function also can be great for browser caching controll. For example, you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a waste of time. Instead, you can do like:
echo ‘. filesize ( dirname ( __FILE__ ). ‘/style.css’ ). ‘.’ . filemtime ( dirname ( __FILE__ ). ‘/style.css’ ). ‘.0″>’ ;
This also can be apply for JS and also images with same name.
6 years ago
Slightly edited version of the function from rommel at rommelsantor dot com. Now it returns a two characters file size which is a bit more convenient to read.
function human_filesize ( $bytes , $decimals = 2 ) $factor = floor (( strlen ( $bytes ) — 1 ) / 3 );
if ( $factor > 0 ) $sz = ‘KMGT’ ;
return sprintf ( «%. < $decimals >f» , $bytes / pow ( 1024 , $factor )) . @ $sz [ $factor — 1 ] . ‘B’ ;
>print human_filesize ( 12 , 0 ); // 12B
print human_filesize ( 1234567890 , 4 ); // 1.1498GB
print human_filesize ( 123456789 , 1 ); // 117.7MB
print human_filesize ( 12345678901234 , 5 ); // 11.22833TB
print human_filesize ( 1234567 , 3 ); // 1.177MB
print human_filesize ( 123456 ); // 120.56KB
?>I removed the P units because strlen doesn’t seem to work as expected with integers longer than 14 digits. Though it might be only my system’s limitation.
6 years ago
/**
* Return file size (even for file > 2 Gb)
* For file size over PHP_INT_MAX (2 147 483 647), PHP filesize function loops from -PHP_INT_MAX to PHP_INT_MAX.
*
* @param string $path Path of the file
* @return mixed File size or false if error
*/
function realFileSize ( $path )
if (! file_exists ( $path ))
return false ;?php
$size = filesize ( $path );
if (!( $file = fopen ( $path , ‘rb’ )))
return false ;//Quickly jump the first 2 GB with fseek. After that fseek is not working on 32 bit php (it uses int internally)
$size = PHP_INT_MAX — 1 ;
if ( fseek ( $file , PHP_INT_MAX — 1 ) !== 0 )
fclose ( $file );
return false ;
>$length = 1024 * 1024 ;
while (! feof ( $file ))
< //Read the file until end
$read = fread ( $file , $length );
$size = bcadd ( $size , $length );
>
$size = bcsub ( $size , $length );
$size = bcadd ( $size , strlen ( $read ));fclose ( $file );
return $size ;
>7 years ago
// best converting the negative number with File Size .
// does not work with files greater than 4GB
//
// specifically for 32 bit systems. limit conversions filsize is 4GB or
// 4294967296. why we get negative numbers? by what the file
// pointer of the meter must work with the PHP MAX value is 2147483647.
// Offset file : 0 , 1 , 2 , 3 , . 2147483647 = 2GB
// to go higher up the 4GB negative numbers are used
// and therefore after 2147483647, we will -2147483647
// -2147483647, -2147483646, -2147483645, -2147483644 . 0 = 4GB
// therefore 0, 2147483647 and -2147483647 to 0. all done 4GB = 4294967296
// the first offset to 0 and the last offset to 0 of 4GB should be added in
// your compute, so «+ 2» for the number of bytes exate .7 years ago
Here is my super fast method of getting >2GB files to output the correct byte size on any version of windows works with both 32Bit and 64Bit.
function find_filesize ( $file )
if( substr ( PHP_OS , 0 , 3 ) == «WIN» )
exec ( ‘for %I in («‘ . $file . ‘») do @echo %~zI’ , $output );
$return = $output [ 0 ];
>
else
$return = filesize ( $file );
>
return $return ;
>//Usage : find_filesize(«path»);
//Example :
echo «File size is : » . find_filesize ( «D:\Server\movie.mp4» ). «» ;
?>10 years ago
This functions returns the exact file size for file larger than 2 GB on 32 bit OS:
function file_get_size ( $file ) //open file
$fh = fopen ( $file , «r» );
//declare some variables
$size = «0» ;
$char = «» ;
//set file pointer to 0; I’m a little bit paranoid, you can remove this
fseek ( $fh , 0 , SEEK_SET );
//set multiplicator to zero
$count = 0 ;
while ( true ) //jump 1 MB forward in file
fseek ( $fh , 1048576 , SEEK_CUR );
//check if we actually left the file
if (( $char = fgetc ( $fh )) !== false ) //if not, go on
$count ++;
> else //else jump back where we were before leaving and exit loop
fseek ( $fh , — 1048576 , SEEK_CUR );
break;
>
>
//we could make $count jumps, so the file is at least $count * 1.000001 MB large
//1048577 because we jump 1 MB and fgetc goes 1 B forward too
$size = bcmul ( «1048577» , $count );
//now count the last few bytes; they’re always less than 1048576 so it’s quite fast
$fine = 0 ;
while( false !== ( $char = fgetc ( $fh ))) $fine ++;
>
//and add them
$size = bcadd ( $size , $fine );
fclose ( $fh );
return $size ;
>
?>6 years ago
function dir_size($file) <
//tested on win 7×64 php 5.4
exec(‘dir /s /a «‘ . $file.'»‘, $inf);
$r=explode(‘ ‘,$inf[count($inf)-2]);
$rr = preg_replace(‘~[^\d]+~’,»,$r[count($r)-2]);
return $rr;
>9 years ago
The simplest and most efficient implemention for getting remote filesize:
4 years ago
Under Windows 10 filesize obviously cannot work with relative path names. Use absolute path instead. $size = filesize(«.\\myfile.txt»); does not work for me while «d:\\MyFiles\\Myfile.txt» will do. The same applys to similar functions like is_file() or stat(). They won’t work correctly unless given an absolute path.
15 years ago
function getSizeFile ( $url ) <
if ( substr ( $url , 0 , 4 )== ‘http’ ) <
$x = array_change_key_case ( get_headers ( $url , 1 ), CASE_LOWER );
if ( strcasecmp ( $x [ 0 ], ‘HTTP/1.1 200 OK’ ) != 0 ) < $x = $x [ 'content-length' ][ 1 ]; >
else < $x = $x [ 'content-length' ]; >
>
else?php>return $x ;
>
?>In case of you have a redirection in the server (like Redirect Permanent in the .htaccess)
In this case we have for exemple:
[content-length] => Array[0] => 294 // Size requested file
[1] => 357556 // Real Size redirected file
7 years ago
// extract filesize with command dir windows 10
// is ok for all system 32/64 and the best compatibility for Dummy file
// but cant return value in (int) for best return use Floatfilesize_dir ( «d:\\test.mkv» ); //11.5GB => return (float) 12401880207
function filesize_dir ( $file ) exec ( ‘dir ‘ . $file , $inf );
$size_raw = $inf [ 6 ];
$size_exp = explode ( » » , $size_raw );
$size_ext = $size_exp [ 19 ];
$size_int = (float) str_replace ( chr ( 255 ), » , $size_ext );
return $size_int ;
>15 years ago
I have created a handy function, using parts of code from kaspernj at gmail dot com and md2perpe at gmail dot com, which should get file sizes > 4GB on Windows, Linux and Mac (at least).
function getSize ( $file ) <
$size = filesize ( $file );
if ( $size < 0 )
if (!( strtoupper ( substr ( PHP_OS , 0 , 3 )) == ‘WIN’ ))
$size = trim (` stat -c%s $file `);
else <
$fsobj = new COM ( «Scripting.FileSystemObject» );
$f = $fsobj -> GetFile ( $file );
$size = $file -> Size ;
>
return $size ;
>
?>4 years ago
The first example given may lead one to assume that this function works with a local filename e.g. $fs = filesize(«error_log») but if you manually delete some text, then save and close the file, the next time you check filesize(«error_log») it will return the original value, because the value is cached for performance reasons. If you didn’t know this, it would look like a nasty bug.
So, everyone tells you to insert clearstatcache() which is supposed to clear the cached value and allow you to retrieve the current file size but it still does nothing and looks like another bug!
However, I found that if you always specify the FULL PATH
e.g. $fs = filesize(«/user/some/path/error_log»);
then clearstatcache() is not even needed.10 years ago
A fast implementation that determines actual file size of large files (>2GB) on 32-bit PHP:
function RealFileSize($fp)
$pos = 0;
$size = 1073741824;
fseek($fp, 0, SEEK_SET);
while ($size > 1)
fseek($fp, $size, SEEK_CUR);if (fgetc($fp) === false)
fseek($fp, -$size, SEEK_CUR);
$size = (int)($size / 2);
>
else
fseek($fp, -1, SEEK_CUR);
$pos += $size;
>
>while (fgetc($fp) !== false) $pos++;
Input is an open file handle. Return value is an integer for file sizes < 4GB, floating-point otherwise.
This starts out by skipping ~1GB at a time, reads a character in, repeats. When it gets into the last GB, it halves the size whenever the read fails. The last couple of bytes are just read in.
Some people might have concerns over this function because $pos will become a floating point number after exceeding integer limits and they know of floating point’s tendencies to be inaccurate. On most computers that correctly implement the IEEE floating point spec, $pos will be accurate out to around 9 *petabytes*. Unless you are working with multi-petabyte files in PHP or the code is executing on strange hardware, this function is going to be more than sufficient. Every part of this function has been carefully crafted to deal with 32-bit deficiencies.
7 years ago
For files bigger then 2 GB use my library called Big File Tools. https://github.com/jkuchar/BigFileTools. More details on stackoverflow: http://stackoverflow.com/a/35233556/631369
8 years ago
Here a function to get the size of a file in a human understanding way with decimal separator, thousand separator, decimals.
function convertFileSize($file, $size=null, $decimals=2, $dec_sep=’.’, $thousands_sep=’,’) if (!is_file($file)) return «El fichero no existe»;
>
$bytes = filesize($file);
$sizes = ‘BKMGTP’;
if (isset($size)) $factor = strpos($sizes, $size[0]);
if ($factor===false) return «El tamaño debe ser B, K, M, G, T o P»;
>
> else $factor = floor((strlen($bytes) — 1) / 3);
$size = $sizes[$factor];
>
return number_format($bytes / pow(1024, $factor), $decimals, $dec_sep, $thousands_sep).’ ‘.$size;
>16 years ago
On 64-bit platforms, this seems quite reliable for getting the filesize of files > 4GB
$a = fopen ( $filename , ‘r’ );
fseek ( $a , 0 , SEEK_END );
$filesize = ftell ( $a );
fclose ( $a );
?>12 years ago
I have a cli script running that use the filesize function on a ssh2_sftp connection. It has the >2Gb limit issue, while it does not have that issue locally. I have managed to get around this by doing a «du -sb» command through ssh2_shell.
The following function takes the ssh2_connect resource and the path as input. It may not be neat, but it solves the problem for the moment.
function fSSHFileSize ( $oConn , $sPath ) <
if( false !== ( $oShell = @ ssh2_shell ( $oConn , ‘xterm’ , null , 500 , 24 , SSH2_TERM_UNIT_CHARS ))) <
fwrite ( $oShell , «du -sb ‘» . $sPath . «‘» . PHP_EOL );
sleep ( 1 );
while( $sLine = fgets ( $oShell )) <
flush ();
$aResult [] = $sLine ;
>
fclose ( $oShell );
$iSize = 0 ;
if( count ( $aResult ) > 1 ) <
$sTemp = $aResult [ count ( $aResult )- 2 ];
$sSize = substr ( $sTemp , 0 , strpos ( $sTemp , chr ( 9 )));
if( is_numeric ( trim ( $sSize ))) <
$iTemp = (int) $sSize ;
if( $iTemp > «2000000000» ) $iSize = $iTemp ;
>
>
return $iSize ;
>
return 0 ;
>
?>7 years ago
// use system windows for give filesize
// best for php 32bit or php 64bit
// I do not know if it works on other windows, but on Windows 10 works well hereecho filesize_cmd ( ‘c:\\’ , ‘log.txt’ ); //return 1135
function filesize_cmd ( $folder , $file ) return exec ( ‘forfiles /p ‘ . $folder . ‘ /m «‘ . $file . ‘» /c «cmd /c echo @fsize»‘ );
>14 years ago
Here’s the best way (that I’ve found) to get the size of a remote file. Note that HEAD requests don’t get the actual body of the request, they just retrieve the headers. So making a HEAD request to a resource that is 100MB will take the same amount of time as a HEAD request to a resource that is 1KB.
$remoteFile = ‘http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror’ ;
$ch = curl_init ( $remoteFile );
curl_setopt ( $ch , CURLOPT_NOBODY , true );
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , true );
curl_setopt ( $ch , CURLOPT_HEADER , true );
curl_setopt ( $ch , CURLOPT_FOLLOWLOCATION , true ); //not necessary unless the file redirects (like the PHP example we’re using here)
$data = curl_exec ( $ch );
curl_close ( $ch );
if ( $data === false ) echo ‘cURL failed’ ;
exit;
>$contentLength = ‘unknown’ ;
$status = ‘unknown’ ;
if ( preg_match ( ‘/^HTTP\/1\.[01] (\d\d\d)/’ , $data , $matches )) $status = (int) $matches [ 1 ];
>
if ( preg_match ( ‘/Content-Length: (\d+)/’ , $data , $matches )) $contentLength = (int) $matches [ 1 ];
>echo ‘HTTP Status: ‘ . $status . «\n» ;
echo ‘Content-Length: ‘ . $contentLength ;
?>Result:
HTTP Status: 302
Content-Length: 88087597 years ago
// File size for windows
// if filesize() php > PHP_INT_MAX (4 294 967 296) :: failled
// filesize_cmd returns the value measured by windows?php
function filesize_cmd ( $file ) $pth = pathinfo ( $file );
$fz = filesize ( $file );
$fx = exec ( ‘forfiles /p ‘ . $pth [ ‘dirname’ ] . ‘ /m «‘ . $pth [ ‘basename’ ] . ‘» /c «cmd /c echo @fsize»‘ );
if( $fz != $fx ) < return $fx ; >
return $fz ;
>3 years ago
// Quick example to test the return value in order to tell a 0 byte file from a failed call to filesize()
?php
$size = filesize ( «some.file» );
if ( $size === FALSE ) echo «filesize not available» ;
> else echo «some.file is $size bytes long» ;
>// A shorter version, slightly different
if ( ( $size = filesize ( «some.file» )) !== FALSE )
echo «some.file is $size bytes long» ;
?>9 years ago
Here ist the very fast and reliable way to get size of large files > 2Gb on 32bit and 64bit platforms.
/**
* Get the size of file, platform- and architecture-independant.
* This function supports 32bit and 64bit architectures and works fith large files > 2 GB
* The return value type depends on platform/architecture: (float) when PHP_INT_SIZE < 8 or (int) otherwise
* @param resource $fp
* @return mixed (int|float) File size on success or (bool) FALSE on error
*/
function my_filesize ( $fp ) $return = false ;
if ( is_resource ( $fp )) if ( PHP_INT_SIZE < 8 ) // 32bit
if ( 0 === fseek ( $fp , 0 , SEEK_END )) $return = 0.0 ;
$step = 0x7FFFFFFF ;
while ( $step > 0 ) if ( 0 === fseek ( $fp , — $step , SEEK_CUR )) $return += floatval ( $step );
> else $step >>= 1 ;
>
>
>
> elseif ( 0 === fseek ( $fp , 0 , SEEK_END )) // 64bit
$return = ftell ( $fp );
>
>
return $return ;
>
?>14 years ago
This is an updated version of my previous filesize2bytes.
The return type now it’s really an int./**
* Converts human readable file size (e.g. 10 MB, 200.20 GB) into bytes.
*
* @param string $str
* @return int the result is in bytes
* @author Svetoslav Marinov
* @author http://slavi.biz
*/
function filesize2bytes ( $str ) <
$bytes = 0 ;$bytes_array = array(
‘B’ => 1 ,
‘KB’ => 1024 ,
‘MB’ => 1024 * 1024 ,
‘GB’ => 1024 * 1024 * 1024 ,
‘TB’ => 1024 * 1024 * 1024 * 1024 ,
‘PB’ => 1024 * 1024 * 1024 * 1024 * 1024 ,
);$bytes = floatval ( $str );
$bytes = intval ( round ( $bytes , 2 ));
17 years ago
some notes and modifications to previous post.
refering to RFC, when using HTTP/1.1 your request (either GET or POST or HEAD) must contain Host header string, opposite to HTTP/1.1 where Host ain’t required. but there’s no sure how your remote server would treat the request so you can add Host anyway (it won’t be an error for HTTP/1.0).
host value _must_ be a host name (not CNAME and not IP address).this function catches response, containing Location header and recursively sends HEAD request to host where we are moved until final response is met.
(you can experience such redirections often when downloading something from php scripts or some hash links that use apache mod_rewrite. most all of dowloading masters handle 302 redirects correctly, so this code does it too (running recursively thru 302 redirections).)[$counter302] specify how much times your allow this function to jump if redirections are met. If initial limit (5 is default) expired — it returns 0 (should be modified for your purposes whatever).0
ReadHeader() function is listed in previous post
(param description is placed there too).function remote_filesize_thru ( $ipAddress , $url , $counter302 = 5 )
<
$socket = fsockopen ( «10.233.225.2» , 8080 );
if( ! $socket )
<
// failed to open TCP socket connection
// do something sensible here besides exit();
echo «
failed to open socket for [ $ipAddress ]» ;
exit();
>// just send HEAD request to server
$head = «HEAD $url HTTP/1.0\r\nConnection: Close\r\n\r\n» ;
// you may use HTTP/1.1 instead, then your request head string _must_ contain «Host: » header
fwrite ( $socket , $head );// read the response header
$header = ReadHeader ( $socket );
if( ! $header )
<
// handle empty response here the way you need.
Header ( «HTTP/1.1 404 Not Found» );
exit();
>// check for «Location» header
$locationMarker = «Location: » ;
$pos = strpos ( $header , $locationMarker );
if( $pos > 0 )
<
$counter302 —;
if( $counter302 < 0 )
<
// redirect limit (5 by default) expired — return some warning or do something sensible here
echo «warning: too long redirection sequence» ;
return 0 ;
>// Location is present — we should determine target host and move there, like any downloading masters do.
// no need to use regex here
$end = strpos ( $header , «\n» , $pos );
$location = trim ( substr ( $header , $pos + strlen ( $locationMarker ), $end — $pos — strlen ( $locationMarker ) ), «\\r\\n» );// extract pure host (without «http://»)
$host = explode ( «/» , $location );
$ipa = gethostbyname ( $host [ 2 ] );
// move to Location
return remote_filesize_thru ( $ipa , $location , $counter302 );
>// try to acquire Content-Length within the response
$regex = ‘/Content-Length:\s([0-9].+?)\s/’ ;
$count = preg_match ( $regex , $header , $matches );// if there was a Content-Length field, its value
// will now be in $matches[1]
if( isset( $matches [ 1 ] ) )
$size = $matches [ 1 ];
else
$size = 0 ;