PHP高级特性2之文件处理
PHP高级特性二之文件处理
PHP中的文件处理也是一个相当重要的模块,这一篇的主要内容就是PHP中文件系统的简介。
文件系统用途
1. 项目处理都离不开文件处理
2. 可以用文件长时间保存数据
3. 建立缓存,在服务器中进行文件操作
文件系统函数用法详述
1.基本的判断函数
is_dir — 判断给定文件名是否是一个目录
is_file — 判断给定文件名是否为一个文件
is_executable — 判断给定文件名是否可执行
is_link — 判断给定文件名是否为一个符号连接
is_readable — 判断给定文件名是否可读
is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的
is_writable — 判断给定的文件名是否可写
is_writeable — is_writable 的别名
2.文件相关信息获取
file_exists — 检查文件或目录是否存在
fileatime — 取得文件的上次访问时间
filectime — 取得文件的 inode 修改时间
filegroup — 取得文件的组
fileinode — 取得文件的 inode
filemtime — 取得文件修改时间
fileowner — 取得文件的所有者
fileperms — 取得文件的权限
filesize — 取得文件大小
filetype — 取得文件类型
下面我们写一个例子,传入文件名,打印它的详细信息。
1 2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
function getFileInfo($filename){
if(!file_exists($filename)){
echo '文件'.($filename).'不存在';
return;
}
if(is_file($filename)){
echo $filename.'是一个文件';
}
if(is_dir($filename)){
echo $filename.'是一个目录';
}
if(is_executable($filename)){
echo $filename.'是可执行文件';
}else{
echo $filename.'不是可执行文件';
}
if(is_readable($filename)){
echo $filename.'是可读的';
}else{
echo $filename.'不是可读的';
}
if(is_writable($filename)){
echo $filename.'是可写入的';
}else{
echo $filename.'不是可写入的';
}
echo '文件'.$filename.'的大小是'.getFileSize(filesize($filename)).'';
echo '文件'.$filename.'的类型是'.filetype($filename).'';
echo '文件'.$filename.'的所有者是'.fileowner($filename).'';
echo '文件'.$filename.'的最后访问时间为'.getTime(fileatime($filename)).'';
echo '文件'.$filename.'的inode是'.fileinode($filename).'';
echo '文件'.$filename.'的修改时间是'.getTime(filemtime($filename)).'';
echo '文件'.$filename.'的权限是'.fileperms($filename).'';
}
function getTime($time){
return date('Y-m-d H:i:s',$time);
}
function getFileSize($size){
$dw = 'B';
if($size>=pow(2,40)){
$size=round($size/pow(2,40),2);
$dw = 'PB';
}else if($size>=pow(2,30)){
$size=round($size/pow(2,30),2);
$dw = 'TB';
}else if($size>=pow(2,20)){
$size=round($size/pow(2,20),2);
$dw = 'GB';
}else if($size>=pow(2,10)){
$size=round($size/pow(2,10),2);
$dw = 'MB';
}
return $size.$dw;
}
getFileInfo('1.php');
|
运行结果
1.php是一个文件
1.php不是可执行文件
1.php是可读的
1.php不是可写入的
文件1.php的大小是2MB
文件1.php的类型是file
文件1.php的所有者是1000
文件1.php的最后访问时间为2015-03-04 12:58:33
文件1.php的inode是536185
文件1.php的修改时间是2015-03-04 12:58:32
文件1.php的权限是33204
3.文件路径相关函数
相对路径:相对于当前目录的上级和下级目录
. 当前目录
.. 上一级目录
路径分隔符号
linux/Unix “/”
windows “\”
不管是什么操作系统PHP的目录分割符号都支技 / (Linux)
绝对路径:可以指的操作系统的根,也可以指的是存放网站的文档根目录
如果是在服务器中执行(通过PHP文件处理函数执行)路径 则 “根”指的就是操作系统的根
如果程序是下载的客户端,再访问服务器中的文件时,只有通过Apache访问,“根”也就指的是文档根目录
三个相关函数
basename — 返回路径中的文件名部分
dirname — 返回路径中的目录部分
pathinfo — 返回文件路径的信息
例如下面的例子
1 2
3
4
5
6
7
8
|
$url1="./aaa/bbb/index.php";
$url2="../www/yyy/login.rar";
$url3="c:/appserv/www/demo.html";
$url4="http://localhost/yyy/www.gif";
echo basename($url1);
echo basename($url2);
echo basename($url3);
echo basename($url4);
|
运行结果
index.php
login.rar
demo.html
www.gif
可以看出,basename这个函数返回的是文件的名,也就是最后一个项目。
下面我们看一下dirname的用法
1 2
3
4
5
6
7
8
|
$url1="./aaa/bbb/index.php";
$url2="../www/yyy/login.rar";
$url3="c:/appserv/www/demo.html";
$url4="http://localhost/yyy/www.gif";
echo dirname(dirname($url1));
echo dirname($url2);
echo dirname($url3);
echo dirname($url4);
|
运行结果
./aaa
../www/yyy
c:/appserv/www
http://localhost/yyy
可以发现,dirname这个函数可以多层嵌套使用,返回的就是它所在的路径,即除了最后一项之外所有的项。
另外 pathinfo的以上所有信息都可以获取到,另外还包括了文件名和扩展名
比如下面的结果
Array ( [dirname] => ../www/yyy [basename] => login.rar [extension] => rar [filename] => login )
4. 文件的创建删除修改
touch — 创建一个文件
unlink — 删除文件
rename — 重命名一个文件或目录
copy — 拷贝文件
例如下面的例子
1 2
3
4
5
|
touch("./php.apahce"); //创建文件
unlink("C:/AppServ/www/xsphp/apache.php"); //删除文件
rename("./test.txt", "d:/test2.txt"); //重命名文件
copy("cache.txt", "./cache5.txt"); //复制文件
chmod("a.txt",755); //设置文件权限
|
权限相关内容
rwx 表这个文件的拥有者 r读 w写 x执行
rwx 表这个文件的拥有者所在的组 r读 w写 x执行
rwx 其它用户对这个为文件的权限 r读 w写 x执行
文件读写
1. file_get_contents(string)
传入文件名,直接得到文件中的文本信息,返回的内容即为文件中的文本。
例如
1 2
3
4
|
$str = file_get_contents("1.txt");
echo $str;
?>
|
则直接打开了 1.txt 文件中的内容,并返回文件中的文本信息。
如果文件不存在,那么会提示
Warning: file_get_contents(2.txt): failed to open stream: No such file or directory
同样,文件还可以是远程文件,例如,参数传入 http://www.qq.com
即可以呈现腾讯网的首页内容。
缺点:不能读取指定部分的内容,一次性全部读取。
2. file_put_contents(filename,content)
写入文件,filename是写入文件的文件名,content是写入内容,返回值是成功写入的字符长度。
1 2
3
|
echo file_put_contents("2.txt",'abcd'); ?>
|
2.txt 文件如果不存在,那么则会创建这个文件并写入 abcd 这个字符串,返回 4 ,为字符串的长度。 如果文件存在,则会将文件清空,然后写入字符串,返回写入长度。
缺点:不能以追加的方式写入文件。
3.file(filename)
file是直接打开某一个文件,返回的结果是一个数组,每一行是数组的一个元素。也就是说,获取行数只需要输出数组的大小即可。例如
1 2
3
4
5
|
$str = file("1.txt");
var_dump($str);
echo count($str);
?>
|
即可得到数组形式的行内容,而且输出了行数。
缺点:不能读取指定部分的内容。
4.fopen(filename,mode)
filename是文件名,可以是路径加名,也可以是远程服务器文件。
mode是打开文件的方式
r,以只读模式打开文件
r+,除了读,还可以写入。
w, 以只写的方式打开,如果文件不存在,则创建这个文件,并写放内容,如果文件存在,并原来有内容,则会清除原文件中所有内容,再写入(打开已有的重要文件)
w+,除了可以写用fwrite, 还可以读fread
a,以只写的方式打开,如果文件不存在,则创建这个文件,并写放内容,如果文件存在,并原来有内容,则不清除原有文件内容,再原有文件内容的最后写入新内容,(追加)
a+,除了可以写用fwrite, 还可以读fread
b,以二进制模式打开文件(图,电影)
t,以文本模式打开文件
注意:
r+具有读写属性,从文件头开始写,保留原文件中没有被覆盖的内容;
w+具有读写属性,写的时候如果文件存在,会被清空,从头开始写。
返回的是一个文件资源
5.fwrite(file,content)
文件写入功能,file是文件资源,用fopen函数获取来的,content是写入内容。同 fputs 函数。
例如
1 2
3
4
5
6
7
8
9
|
php
$file = fopen("1.txt","r+");
$result = fwrite($file,"xx");
if($result){
echo "Success";
}else
echo "Failed";
}
?>
|
则从头开始写入资源,即把前两个字符设为 xx
6. fread(file,size)
读取文件指定部分的长度,file是文件资源,由fopen返回的对象,size是读取字符的长度。
例如
1 2
3
4
5
|
$file = fopen("1.txt","r");
$content = fread($file,filesize("1.txt"));
echo $content;
?>
|
不过,上述的 filesize 方法只能获取本地文件大小,对于远程文件的读取就要换一种方法了。
例如
1 2
3
4
5
6
7
8
|
$file = fopen("http://www.qq.com","r");
$str = "";
while(!feof($file)){ //判断时候到了文件结尾
$str.=fread($file,1024);
}
echo $str;
?>
|
7.fgets(file)
file是文件资源,每次读取一行。例如我们读取出腾讯首页一共有多少行。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode
