zq_g...@sohu.com
unread,Feb 28, 2008, 9:08:58 AM2/28/08Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to 说你说我
目录,文件操作详谈—php
● 写文件
和读取文件的方式一样,先看看是不是能写:
<?php
$file = 'dirlist.php';
if (is_writable($file) == false) {
die("我是鸡毛,我不能");
}
?>
能写了的话可以使用file_put_contents函数写入:
<?php
$file = 'dirlist.php';
if (is_writable($file) == false) {
die('我是鸡毛,我不能');
}
$data = '我是可鄙,我想要';
file_put_contents ($file, $data);
?>
file_put_contents函数在php5中新引进的函数(不知道存在的话用function_exists函数先判断一下)低版本的php无
法使用,可以使用如下方式:
$f = fopen($file, 'w');
fwrite($f, $data);
fclose($f);
替换之.
写文件的时候有时候需要锁定,然后写:
function cache_page($pageurl,$pagedata){
if(!$fso=fopen($pageurl,'w')){
$this->warns('无法打开缓存文件.');//trigger_error
return false;
}
if(!flock($fso,LOCK_EX)){//LOCK_NB,排它型锁定
$this->warns('无法锁定缓存文件.');//trigger_error
return false;
}
if(!fwrite($fso,$pagedata)){//写入字节流,serialize写入其他格式
$this->warns('无法写入缓存文件.');//trigger_error
return false;
}
flock($fso,LOCK_UN);//释放锁定
fclose($fso);
return true;
}
● 复制,删除文件
php删除文件非常easy,用unlink函数简单操作:
<?php
$file = 'dirlist.php';
$result = @unlink ($file);
if ($result == false) {
echo '蚊子赶走了';
} else {
echo '无法赶走';
}
?>
即可.
复制文件也很容易:
<?php
$file = 'yang.txt';
$newfile = 'ji.txt'; # 这个文件父文件夹必须能写
if (file_exists($file) == false) {
die ('小样没上线,无法复制');
}
$result = copy($file, $newfile);
if ($result == true) {
echo '复制记忆ok';
}
?>
可以使用rename()函数重命名一个文件夹.其他操作都是这几个函数组合一下就能实现的.
● 获取文件属性
我说几个常见的函数:
获取最近修改时间:
<?php
$file = 'test.txt';
echo date('r', filemtime($file));
?>
返回的说unix的时间戳,这在缓存技术常用.
相关的还有获取上次被访问的时间fileatime(),filectime()当文件的权限,所有者,所有组或其它 inode 中的元数据被更新时
间,fileowner()函数返回文件所有者
$owner = posix_getpwuid(fileowner($file));
(非window系统),ileperms()获取文件的权限,
<?php
$file = 'dirlist.php';
$perms = substr(sprintf('%o', fileperms($file)), -4);
echo $perms;
?>
filesize()返回文件大小的字节数:
<?php
// 输出类似:somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
?>
获取文件的全部信息有个返回数组的函数stat()函数:
<?php
$file = 'dirlist.php';
$perms = stat($file);
var_dump($perms);
?>
那个键对应什么可以查阅详细资料,此处不再展开.
===========================
截取路径中的文件名技巧
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to
"index.php"
$file = basename($path,".php"); // $file is set to "index"
?>
==========================
获取正在执行文件的文件名
<?php
echo __FILE__;
?>