我编写了一个简单的备份脚本,它将文件夹(及其所有子文件夹)中的所有文件放在一个 TAR 存档中...
(它是经典的 TAR 格式,不是 USTAR,因此文件名及其路径不能超过 99 个字符)
<?php
类 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("所用时间:%f 秒", ($finish_time - $start_time));
?>