This article mainly introduces the file and directory operations of PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
php file directory operations
Directory operation
function traversal_dir($path, $deep = 0) { if (is_dir($path)) { $handle = opendir($path); while (($file = readdir($handle)) !== false) { if ($file == '.' || $file == '..') { continue; } echo str_repeat('-', 2 * $deep) . $file . '</br>'; if (is_dir($path . '/' . $file)) { traversal_dir($path . '/' . $file, $deep + 1); } } } } traversal_dir('./');
File operations
is_file ($path): Determine whether the specified path is a file
##file_exists ($path): Check whether the directory or file exists
##fopen ($file):resource $handle , int
$length ): Read the file, the length can be specified
##fwrite ( resource $handle , string $string
[, int $length
] ): Returns the size of the written string. If length is specified, when length
bytes are written or After writing string
, writing will stop, depending on which situation is encountered first.
fgets ( resource $handle [, int $length ] ): Read a line of text, length specifies the length of a line of text
##fclose (
basename ($path): Returns the file name part of the specified path Returns String
##Judgment part
#filesize ( $path ) Get the file size int
filetype ( $path ) gets the file type string (possible values: fifo, char, dir, block, link, file and unknown)
rename ( string $oldname
,$newname [, resource $context
] ) Rename or move Return Boolean
unlink ( $path ) 删除文件 返回布尔
file_get_contents 将整个文件读如一个字符串
file_put_contents 将一个字符串写入文件
代码:每执行一次文件,向文件头部追加 Hello word
$path = './hello.txt'; if (!file_exists($path)) { $handle = fopen($path, 'w+'); fwrite($handle, 'Hello word' . '\r\n'); fclose($handle); } else { $handle = fopen($path, 'r'); $content = fread($handle, filesize($path)); $content = 'Hello word \r\n' . $content; fclose($handle); $handle = fopen($path, 'w'); fwrite($handle, $content); fclose($handle); }
代码:遍历删除文件夹及文件夹下所有文件
function traversal_delete_dir($path) { if (is_dir($path)) { $handle = opendir($path); while (($file = readdir($handle)) !== false) { if ($file == '.' || $file == '..') { continue; } if (is_dir($path . '/' . $file)) { traversal_delete_dir($path . '/' . $file); } else { if (unlink($path . '/' . $file)) { echo '删除文件' . $file . '成功'; } } } closedir($handle); rmdir($path); } } traversal_delete_dir('./shop_api');
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of PHP file and directory operations. For more information, please follow other related articles on the PHP Chinese website!