PHP Conference Japan 2024

目录函数

参见

有关诸如 dirname()is_dir()mkdir()rmdir() 的相关函数,请参阅 文件系统 部分。

目录

  • chdir — 更改目录
  • chroot — 更改根目录
  • closedir — 关闭目录句柄
  • dir — 返回 Directory 类的实例
  • getcwd — 获取当前工作目录
  • opendir — 打开目录句柄
  • readdir — 从目录句柄读取条目
  • rewinddir — 倒回目录句柄
  • scandir — 列出指定路径内的文件和目录
添加注释

用户贡献的注释 1 条注释

dkflbk at nm dot ru
18 年前
我编写了一个简单的备份脚本,它将文件夹(以及所有子文件夹)中的所有文件都放到一个 TAR 归档文件中……
(它是经典的 TAR 格式,而不是 USTAR,因此文件名和路径不能超过 99 个字符)


<?php
/***********************************************************
* 标题:基于 Classic-TAR 的备份脚本 v0.0.1-dev
**********************************************************/

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('错误');
$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("所用时间:%f 秒", ($finish_time - $start_time));
?>
To Top