php笔记之常用文件操作
<?php |
02 |
//常用文件操作函数 |
03 |
|
04 |
//第一部分 文件读写 与创建 删除 重命名等 |
05 |
//在开始前操作文件前 我们先判断一下是否是个文件 文件是否可执行 可读 可写 |
06 |
$file="test.txt"; |
07 |
if(file_exists($file))//盘断文件是否存在 |
08 |
{ |
09 |
echo "文件存在<br>"; |
10 |
}else |
11 |
{ |
12 |
echo "文件不存在,已创建"; |
13 |
$fp=fopen($file,"w");//只读模式创建 |
14 |
fclose($fp); |
15 |
} |
16 |
if(is_file($file)) |
17 |
{ |
18 |
echo "是文件<br>"; |
19 |
} |
20 |
if(is_dir($file)) |
21 |
{ |
22 |
echo "是目录<br>"; |
23 |
} |
24 |
|
25 |
if(is_executable($file)) |
26 |
{ |
27 |
echo "文件可执行<br>"; |
28 |
} |
29 |
if(is_readable($file)) |
30 |
{ |
31 |
echo "文件可读<br>"; |
32 |
} |
33 |
if(is_writable($file)) |
34 |
{ |
35 |
echo "文件可写<br>"; |
36 |
} |
37 |
chmod($file,0777);//完全权限 |
38 |
//模式说明 数字 1 表示使文件可执行,数字 2 表示使文件可写,数字 4 表示使文件可读--模式相加代表权限 |
39 |
$fp=fopen("test.txt","a+");//用追加读写的方式打开 |
40 |
//打开远程文件时 |
41 |
//$fp=fopen("test.txt","a+b");记得加b; |
42 |
$content=fread($fp,70);//读取70字节 |
43 |
echo "1.{$content}<br> ";//输出 |
44 |
fwrite($fp,"我是<a href='http://www.jianlila.com'>荐礼啦</a>asdddddddddddddddddddddddddddddddddxxxxxxxxx");//已追加方式写入 |
45 |
$content=file_get_contents("test.txt");//读取文件 读取远程文件推荐用此函数 |
46 |
//$content=file_get_contents("http://www.jianlila.com"); |
47 |
echo "2.{$content}<br> "; |
48 |
file_put_contents("test.txt","我是<a href='http://www.aiwobama.com'>爱我爸妈</a>asdddddddddddddddddddddddddddddddddxxxxxxxxx"); |
49 |
//输出到文件 |
50 |
fclose($fp);//关闭文件句柄 |
51 |
$fp=fopen("test.txt","a+"); |
52 |
$content=fread($fp,filesize("test.txt")); |
53 |
//读取全部内容 filesize($file)//文件字节数 |
54 |
echo "3.{$content}<br>"; |
55 |
$fp=fopen("test.txt","r"); |
56 |
echo "一个字符".fgetc($fp)."<br>";//读取一个字符 |
57 |
$fp=fopen("test.txt","r"); |
58 |
echo "一行".fgets($fp)."<br>";//读取一行字符 |
59 |
$fp=fopen("test.txt","r"); |
60 |
echo "剩余数据"; |
61 |
fpassthru($fp); |
62 |
echo "<br>";//输出剩余数据 可以用来输出二进制文件 |
63 |
copy("test.txt","荐礼啦.txt"); |
64 |
//文件拷贝 |
65 |
if(file_exists("爱我爸妈.txt")) |
66 |
{ |
67 |
unlink("爱我爸妈.txt"); |
68 |
//如果存在则删除文件 |
69 |
} |
70 |
rename("荐礼啦.txt","爱我爸妈.txt"); |
71 |
//文件重命名 |
72 |
|
73 |
if(file_exists("荐礼啦")) |
74 |
{ |
75 |
rmdir("荐礼啦");//删除文件夹 |
76 |
}else |
77 |
{ |
78 |
mkdir("荐礼啦");//创建文件夹 |
79 |
} |
80 |
|
81 |
|
82 |
//获取文件信息 函数 |
83 |
$file="test.txt"; |
84 |
echo "文件大小".filesize($file)."字节<br>"; |
85 |
echo "文件类型".filetype($file)."<br>"; |
86 |
//这里的文件类型不是我们看到的.txt这类 二十指fifo,char,dir,block,link,file 和 unknown |
87 |
$fp=fopen($file,"r");//打开文件 |
88 |
print_r(fstat($fp));//打印文件信息 |
89 |
echo "当前文件路径信息".__FILE__."<br>"; |
90 |
echo "当前文件所在的目录".dirname(__FILE__)."<br>"; |
91 |
echo "当前文件名".basename(__FILE__)."<br>"; |
92 |
print_r(stat($file));//打印文件信息 |
93 |
|
94 |
?> |
浙公网安备 33010602011771号