PHP高級特性2之文件處理
Jun 13, 2016 pm 12:21 PM
PHP高級特性二之文件處理
PHP中的文件處理也是一個(gè)相當(dāng)重要的模塊,這一篇的主要內(nèi)容就是PHP中文件系統(tǒng)的簡介。
文件系統(tǒng)用途
1. 項(xiàng)目處理都離不開文件處理
2. 可以用文件長時(shí)間保存數(shù)據(jù)
3. 建立緩存,在服務(wù)器中進(jìn)行文件操作
文件系統(tǒng)函數(shù)用法詳述
1.基本的判斷函數(shù)
is_dir?— 判斷給定文件名是否是一個(gè)目錄
is_file?— 判斷給定文件名是否為一個(gè)文件
is_executable?— 判斷給定文件名是否可執(zhí)行
is_link?— 判斷給定文件名是否為一個(gè)符號連接
is_readable?— 判斷給定文件名是否可讀
is_uploaded_file?— 判斷文件是否是通過 HTTP POST 上傳的
is_writable?— 判斷給定的文件名是否可寫
is_writeable?— is_writable 的別名
2.文件相關(guān)信息獲取
file_exists?— 檢查文件或目錄是否存在
fileatime?— 取得文件的上次訪問時(shí)間
filectime?— 取得文件的 inode 修改時(shí)間
filegroup?— 取得文件的組
fileinode?— 取得文件的 inode
filemtime?— 取得文件修改時(shí)間
fileowner?— 取得文件的所有者
fileperms?— 取得文件的權(quán)限
filesize?— 取得文件大小
filetype?— 取得文件類型
下面我們寫一個(gè)例子,傳入文件名,打印它的詳細(xì)信息。
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.'是一個(gè)文件';
????????}
?
????????if(is_dir($filename)){
????????????echo $filename.'是一個(gè)目錄';
????????}
?
????????if(is_executable($filename)){
????????????echo $filename.'是可執(zhí)行文件';
????????}else{
????????????echo $filename.'不是可執(zhí)行文件';
????????}
?
????????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.'的最后訪問時(shí)間為'.getTime(fileatime($filename)).'';
????????echo '文件'.$filename.'的inode是'.fileinode($filename).'';
????????echo '文件'.$filename.'的修改時(shí)間是'.getTime(filemtime($filename)).'';
????????echo '文件'.$filename.'的權(quán)限是'.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');
|
運(yùn)行結(jié)果
1.php是一個(gè)文件
1.php不是可執(zhí)行文件
1.php是可讀的
1.php不是可寫入的
文件1.php的大小是2MB
文件1.php的類型是file
文件1.php的所有者是1000
文件1.php的最后訪問時(shí)間為2015-03-04 12:58:33
文件1.php的inode是536185
文件1.php的修改時(shí)間是2015-03-04 12:58:32
文件1.php的權(quán)限是33204
?3.文件路徑相關(guān)函數(shù)
相對路徑:相對于當(dāng)前目錄的上級和下級目錄
. 當(dāng)前目錄
.. 上一級目錄
路徑分隔符號
linux/Unix “/”
windows “\”
不管是什么操作系統(tǒng)PHP的目錄分割符號都支技 / (Linux)
絕對路徑:可以指的操作系統(tǒng)的根,也可以指的是存放網(wǎng)站的文檔根目錄
如果是在服務(wù)器中執(zhí)行(通過PHP文件處理函數(shù)執(zhí)行)路徑 則 “根”指的就是操作系統(tǒng)的根
如果程序是下載的客戶端,再訪問服務(wù)器中的文件時(shí),只有通過Apache訪問,“根”也就指的是文檔根目錄
三個(gè)相關(guān)函數(shù)
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);
|
運(yùn)行結(jié)果
index.php
login.rar
demo.html
www.gif
可以看出,basename這個(gè)函數(shù)返回的是文件的名,也就是最后一個(gè)項(xiàng)目。
下面我們看一下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);
|
運(yùn)行結(jié)果
./aaa
../www/yyy
c:/appserv/www
http://localhost/yyy
可以發(fā)現(xiàn),dirname這個(gè)函數(shù)可以多層嵌套使用,返回的就是它所在的路徑,即除了最后一項(xiàng)之外所有的項(xiàng)。
另外 pathinfo的以上所有信息都可以獲取到,另外還包括了文件名和擴(kuò)展名
比如下面的結(jié)果
Array ( [dirname] => ../www/yyy [basename] => login.rar [extension] => rar [filename] => login )
4. 文件的創(chuàng)建刪除修改
touch?— 創(chuàng)建一個(gè)文件
unlink?— 刪除文件
rename?— 重命名一個(gè)文件或目錄
copy?—?拷貝文件
例如下面的例子
1 2
3
4
5
|
touch("./php.apahce"); //創(chuàng)建文件
unlink("C:/AppServ/www/xsphp/apache.php");??//刪除文件
rename("./test.txt", "d:/test2.txt");????//重命名文件
copy("cache.txt", "./cache5.txt");?? //復(fù)制文件
chmod("a.txt",755);?? //設(shè)置文件權(quán)限
|
權(quán)限相關(guān)內(nèi)容
rwx 表這個(gè)文件的擁有者 r讀 w寫 x執(zhí)行
rwx 表這個(gè)文件的擁有者所在的組 r讀 w寫 x執(zhí)行
rwx 其它用戶對這個(gè)為文件的權(quán)限 r讀 w寫 x執(zhí)行
文件讀寫
1. file_get_contents(string)
傳入文件名,直接得到文件中的文本信息,返回的內(nèi)容即為文件中的文本。
例如
1 2
3
4
|
$str = file_get_contents("1.txt");
echo $str;
?>
|
則直接打開了 1.txt 文件中的內(nèi)容,并返回文件中的文本信息。
如果文件不存在,那么會提示
Warning: file_get_contents(2.txt): failed to open stream: No such file or directory
同樣,文件還可以是遠(yuǎn)程文件,例如,參數(shù)傳入 http://www.qq.com
即可以呈現(xiàn)騰訊網(wǎng)的首頁內(nèi)容。
缺點(diǎn):不能讀取指定部分的內(nèi)容,一次性全部讀取。
2. file_put_contents(filename,content)
寫入文件,filename是寫入文件的文件名,content是寫入內(nèi)容,返回值是成功寫入的字符長度。
1 2
3
|
echo file_put_contents("2.txt",'abcd'); ?>
|
2.txt 文件如果不存在,那么則會創(chuàng)建這個(gè)文件并寫入 abcd 這個(gè)字符串,返回 4 ,為字符串的長度。 如果文件存在,則會將文件清空,然后寫入字符串,返回寫入長度。
缺點(diǎn):不能以追加的方式寫入文件。
3.file(filename)
file是直接打開某一個(gè)文件,返回的結(jié)果是一個(gè)數(shù)組,每一行是數(shù)組的一個(gè)元素。也就是說,獲取行數(shù)只需要輸出數(shù)組的大小即可。例如
1 2
3
4
5
|
$str = file("1.txt");
var_dump($str);
echo count($str);
?>
|
即可得到數(shù)組形式的行內(nèi)容,而且輸出了行數(shù)。
缺點(diǎn):不能讀取指定部分的內(nèi)容。
4.fopen(filename,mode)
filename是文件名,可以是路徑加名,也可以是遠(yuǎn)程服務(wù)器文件。
mode是打開文件的方式
r,以只讀模式打開文件
r+,除了讀,還可以寫入。
w, 以只寫的方式打開,如果文件不存在,則創(chuàng)建這個(gè)文件,并寫放內(nèi)容,如果文件存在,并原來有內(nèi)容,則會清除原文件中所有內(nèi)容,再寫入(打開已有的重要文件)
w+,除了可以寫用fwrite, 還可以讀fread
a,以只寫的方式打開,如果文件不存在,則創(chuàng)建這個(gè)文件,并寫放內(nèi)容,如果文件存在,并原來有內(nèi)容,則不清除原有文件內(nèi)容,再原有文件內(nèi)容的最后寫入新內(nèi)容,(追加)
a+,除了可以寫用fwrite, 還可以讀fread
b,以二進(jìn)制模式打開文件(圖,電影)
t,以文本模式打開文件
注意:
r+具有讀寫屬性,從文件頭開始寫,保留原文件中沒有被覆蓋的內(nèi)容;
w+具有讀寫屬性,寫的時(shí)候如果文件存在,會被清空,從頭開始寫。
返回的是一個(gè)文件資源
5.fwrite(file,content)
文件寫入功能,file是文件資源,用fopen函數(shù)獲取來的,content是寫入內(nèi)容。同 fputs 函數(shù)。
例如
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";
}
?>
|
則從頭開始寫入資源,即把前兩個(gè)字符設(shè)為 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 方法只能獲取本地文件大小,對于遠(yuǎn)程文件的讀取就要換一種方法了。
例如
1 2
3
4
5
6
7
8
|
$file = fopen("http://www.qq.com","r");
$str = "";
while(!feof($file)){ ?//判斷時(shí)候到了文件結(jié)尾
$str.=fread($file,1024);
}
echo $str;
?>
|
?
7.fgets(file)
file是文件資源,每次讀取一行。例如我們讀取出騰訊首頁一共有多少行。

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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

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

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

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"

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

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

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using
