Basic PHP development tutorial: PHP file operations
1. File system
1. We will right-click the mouse to delete the file, control+c (or right-click) to copy and paste the file, and create a new file. For some files, check whether the file is read-only.
2. It would be great if these operations performed in the computer can be performed in the code.
3. Because, if there are these operations. We can do a lot of things:
Can I write and modify the configuration file?
Is it possible to detect file permissions during PHP installation?
Is it possible to generate Html files and many other operations
... File operations are used in too many other places.
4. Learning file processing is essentially learning file processing functions. Combine it with the code you wrote before to improve your business processing capabilities.
2. Read the file
1.readfile reads the file
So how to read a file? Let's learn a function first.
int readfile (string $filename)
Function: Pass in a file path and output a file.
In the code below, the file is read as long as the file name or the specified file path is passed in.
<?php //linux类的读了方式 readfile("/home/paul/test.txt"); //windows类的读取方式 readfile("c:\boot.ini"); ?>
Note: The windows slash in the above code is \slash, which may escape some characters. Therefore, when we write, we write two slashes.
2.file_get_contents opens the file
The above is a direct output after simply opening the file. Is there any operation that can be assigned to a variable after opening the file? The way.
PHP will certainly provide this method. This method is one of the ways PHP opens a file and returns the content. Let’s take a look at the function:
string file_get_contents (string filename)
Function: Pass Enter a file or file path, open the file and return the contents of the file. The content of the file is a string.
<?php $filename = 'NoAlike.txt'; $filestring = file_get_contents($filename); echo $filestring; ?>
The above code opens a file and outputs the contents of the file.
Let’s expand the code based on the previous knowledge. Use your previous knowledge.
<?php //假设我们有一个多行的文件叫NoAlike.txt,没有的话你可以新建一个这个文件 $filename = 'NoAlike.txt'; //打开这个文件,将文件内容赋值给$filestring $filestring = file_get_contents($filename); //因为每一行有一个回车即\n,我用\n来把这个字符串切割成数组 $filearray = explode("\n", $filestring); //把切割成的数组,下标赋值给$key,值赋值给$val,每次循环将$key加1。 while (list($key, $val) = each($filearray)) { ++$key; $val = trim($val); //用的单引号,单引号不解释变量进行了拼接而已 print 'Line' . $key .':'. $val.'<br />'; } ?>
Above, we have combined the knowledge we have learned before.
3. The fopen, fread, and fclose operations read files
The above file_get_contents method of opening files is simple and crude. The following
resource fopen (string $file name, string mode)
string fread (resource $operation resource, int read length)
bool fclose (resource $operation resource)
Through the above function, we will explain the usual operation methods of resource types:
Open resources
Use related functions to operate
Close resources
fopen function The function of the fopen function is to open a file. There are two main parameters:
l The path to open the file
l Open The pattern of the file
The return type is a resource type. For the first time, we encountered the resource type mentioned in the previous basic type.
The resource type requires other functions to operate this resource. All resources must be closed when they are opened.
fread function The function of the function is to read the open file resource. Read the file resource of the specified length, read part of it and move part backward. to the end of the file.
fclose function The function of the fclose function is to close resources. Resources are opened and closed.
After understanding the functions, the last two functions are relatively simple. What are the modes of the fopen function? The modes of fopen are as follows. Let’s talk about the modes of fopen:
#3. Only after we know how to read files can we have a good grasp of writing files.
1.Open the file
<?php //你可以创建一个NoAlike.txt,以只读模式打开 $fp = fopen('NoAlike.txt', "r"); //var_dump()操作一下$fp看看效果,输出的是不是只有类型提示的是resource var_dump($fp); ?>
2.Read the file
<?php $fp = fopen('NoAlike.txt', "r"); //打开一个文件类型后,读取长度 $contents = fread($fp, 1024); ?>
3. Close the file
<?php $fp = fopen($filename, 'r'); $contents = fread($fp, 1024); fclose($fp); echo $contents; ?>Other notes:
<?php $fp = fopen($filename, 'ab'); $contents = fwrite($fp, '可爱的很\n哟'); fclose($fp); echo $contents; ?>
Note: The experiment cannot allow the naked eye to see the effect of this experiment. Just remember this feature.
Corresponding to this, you can also use 'b' to force binary mode so that the data will not be converted. To use these flags, use either 'b' or 't' as the last character of the mode argument.
4. Create and modify file contents
1.file_put_contents writes to file
Let’s first learn the first way to write a file:int file_put_contents (string $file path, string $write data])
Function: Write a string to the specified file, and create the file if it does not exist. What is returned is the length of written bytes
<?php $data = "我是一个兵,来自老百姓"; $numbytes = file_put_contents('binggege.txt', $data); if($numbytes){ echo '写入成功,我们读取看看结果试试:'; echo file_get_contents('binggege.txt'); }else{ echo '写入失败或者没有权限,注意检查'; } ?>We found that writing files is quite simple. According to the format of this function, specify the file and write the string data.
2.fwrite cooperates with fopen to perform writing operations
int fwrite (resource $File resource variable, string $Written string [, int length ])
Note: The alias function of fwrite is fputsWe tried r mode in the last class, which was only used when reading. Next, we use fwrite plus w in fopen to write files in write mode.
Let’s take a look at the features:
Open the writing mode, point the file pointer to the file header and cut the file size to zero. If the file does not exist then attempts to create it.
Note: In the following experiment, you can try to create a new test.txt file and write content into it. Then, you can try to delete test.txt. See what tips there are.
<?php $filename = 'test.txt'; $fp= fopen($filename, "w"); $len = fwrite($fp, '我是一只来自南方的狼,一直在寻找心中的花姑娘'); fclose($fp); print $len .'字节被写入了\n"; ?>
Summary:
1. Regardless of whether there is a new file, the file will be opened and rewritten
2. The original file content will be overwritten
3. File If it does not exist, it will be created.
Then let’s compare the differences between the following modes:
Let’s prove it through experiments:
<?php $filename = 'test.txt'; $fp= fopen($filename, "r+"); $len = fwrite($fp, '我是一只来自南方的狼,一直在寻找心中的花姑娘'); fclose($fp); print $len .'字节被写入了\n'; ?>
You can remove the + sign after r when experimenting.
Through experiments, we have indeed found that using r mode, data can be written when the file is saved. If only r is used, the writing is unsuccessful.
3. The difference between a mode and w mode
The same is the code below, we change it to a mode.
<?php $filename = 'test.txt'; $fp= fopen($filename, "a"); $len = fwrite($fp,'读大学迷茫了,PHP学院PHP给你希望'); echo $len .'字节被写入了\n'; ?>
Open the web page and execute this code, you will find: every time it is refreshed, there will be an extra paragraph in the file
If you are confused in college, PHP Academy PHP gives you hope.
Summary:
##4. The difference between x mode and w mode
We will experiment with this code again Once, change to x mode:<?php $filename = 'test.txt'; $fp= fopen($filename, "x"); $len = fwrite($fp,'读大学迷茫了,PHP学院PHP给你希望'); echo $len .'字节被写入了\n'; ?>
We will find:
An error will be reported when the file exists
If you change $filename to another file name, it will be fine. However, when I refreshed it again, an error was reported
x+ is the enhanced x mode. Can also be used when reading.
#5. Create temporary files The files we created before are permanent files.
Creating temporary files is also very useful in our daily project development. Several benefits of creating temporary files:
1. Delete it after finishing writing2. There is no need to maintain the deletion status of this file
For example: I need to transfer the file contents of A to B, and transfer the file contents of B to C.
Just like in real life, I can first use a temporary bottle to fill B's water, and then write A's data into B. Add the water from the temporary bottle to C.
Let’s learn this function:
resource tmpfile ( )Function: Create a temporary file and return the resource type. The file is deleted when it is closed.
<?php
//创建了一个临时文件
$handle = tmpfile();
//向里面写入了数据
$numbytes = fwrite($handle, '写入临时文件');
//关闭临时文件,文件即被删除
fclose($handle);
echo '向临时文件中写入了'.$numbytes . '个字节';
?>
## 6. Move, copy and delete files 1. Rename bool rename ($old name,$new name); This function returns a bool value to change the old name to the new name. We open the directory and we can see the effect. You will find that the specified file is copied to the target path. 2. Copy files Copying files is equivalent to cloning technology, cloning an original thing into a new thing. Both look exactly the same. bool copy(source file, target file) Function: Copy the source file with the specified path to the location of the target file. Let’s play it through experiments and code: Summary: 3. Delete files Deleting a file means deleting a file in the specified path, but this deletion is direct deletion. If you are using a Windows computer, you cannot see this file in the Recycle Bin. You will only find that this file has disappeared. bool unlink (file with specified path) 7. Detect file attribute function Some students are particularly curious about where to use file attribute detection. Detecting file attributes can be used in too many places. Let’s give an example: 1. When we install the software, you will find that if the file exists, it will jump to another place. 2. If some files do not have write permission during the installation process, the installation will not be allowed. Let’s take a screenshot of the installation process of discuz, a very famous software in China: The above example is a typical file detection usage. Let’s learn the following batch of functions. Then, let's learn through an example. bool file_exists ($specifies the file name or file path) bool is_readable ($specifies the file name or file path) bool is_writeable ($specifies the file name or file path) bool is_executable ($specifies the file name or file path) bool is_file ($specifies the file name or file path) bool is_dir ($specifies the file name or file path) void clearstatcache (void) The above function can be seen at a glance Clear. As for the experiment, let’s write the example we gave at the beginning. Let’s talk about the first example, file lock. If it has been installed, if the installation lock exists, it will prompt that it has been installed, otherwise, the installation will continue. We assume that the URL of the installation interface is: install.php, and the installed lock file is install.lock. We can detect whether the install.lock file exists. Let’s do a file installation detection experiment to detect whether the file or directory has write or read permissions. If not, the installation cannot be performed. The idea of handling this matter is as follows: 1. Define a batch of arrays that need to detect permissions 2. You can detect whether it is a folder or a file 3. Make a set variable. If the set variable is false, the next step of installation will not be displayed. Through the above example, we have done it. Implement installation detection during the installation process of a certain PHP software. This is the realization of our above ideas. 8. Common functions and constants for files 1. Constants for file operations The following constant is the most commonly used. Is a constant that is the delimiter of the file directory. Let’s take a look at the format: The path format of windows is d:\xxx\xxx Note: Windows supports d:/xxx/xxx We will use a constant: Let’s write a small example to define the path of the current file: Since FILE is a preset of PHP Constants are defined, so there is no way to change them. If necessary, FILE can also adapt to the operating system. 2. File pointer operation function rewind (resource handle) Function: The pointer returns to the beginning ##fseek (resource handle, int offset [, int from_where] )Function: Move the file pointer backward by the specified character We can start an experiment. In the above example, you will find that fseek will move as many bytes as the specified length. And rewind returns to the beginning of the file every time. How to move to the end? We can count the number of bytes. Move directly to the back during fseek. Let’s talk about filesize statistics bytes. 3.filesize detects the size of the file 4.Other functions for operating files In fact, there are some other functions for operating files, read Get the file We use an example to use all the above functions. We write a batch of files in the demo.txt file: abcdeefghijklk fgets opens one line at a time: With the above code, you will find that each time it is read, it opens one line at a time. The final read return is false. Let’s look at the file interception function next: In the above example, we found that the content can be displayed as long as it is intercepted. 5. Time function of file ##9. File lock mechanism Answer: Because the computer operates so fast, basically on the millisecond level. So this experiment actually has no effect. In this case, if a certain collision probability is encountered, I don’t know whose operation will prevail. Note: Regardless of whether the file lock is added, be careful to release it. bool flock ( resource $handle , int $operation) Function: Light consultation file locking<?php
//旧文件名
$filename = 'test.txt';
//新文件名
$filename2 = $filename . '.old';
//复制文件
rename($filename, $filename2);
?>
<?php
//旧文件名
$filename = 'copy.txt';
//新文件名
$filename2 = $filename . '_new';
//修改名字。
copy($filename, $filename2);
?>
You will find that there is an extra file through the above example. <?php
$filename = 'test.txt';
if (unlink($filename)) {
echo "删除文件成功 $filename!\n";
} else {
echo "删除 $filename 失败!\n";
}
?>
Function: whether the file exists.
Function: whether the file is readable
Function: whether the file is writable
Function: whether the file is executable
Function: whether it is a file
Function: Whether it is a directory
Function: Clear the status cache of the file<?php
if(file_exists('install.lock')){
echo '已安装,请不要再次进行安装';
exit;
}
?>
<?php
//可以定义一批文件是否存在
$files = [
'config.php',
'img/',
'uploads/',
];
//定义标志位变量
$flag = true;
foreach($files as $v){
echo $v;
//判断是文件还是文件夹
if(is_file($v)){
echo '是一个文件 ';
}else if(is_dir($v)){
echo '是一个文件夹 ';
}
if(is_readable($v)){
echo ' 可读';
}else{
echo '<font color="red">不可读</font>';
}
if(is_writeable($v)){
echo '可写';
}else{
echo '<font color="red">不可写</font>';
}
echo '<br />';
}
if($flag){
echo '<a href="step1">下一步</a>';
}else{
echo '不能进行安装';
}
?>
The path format of linux is /home/xxx/xxx Note: If \home\xxx\xxx is wrong on linux
So when you enable escape and the like, the escape character \ is used together with d:\ xxx\xxx are the same. When judging, if there are two \, convert it into one \ and replace the \ with / to split the path, so that the paths on Linux or Windows can remain unified.
DIRECTORY_SEPARATOR
Then don’t use FILE. You can use custom constants and process FILE as follows: <?php
$_current_file = str_replace(array('/', '\'), DIRECTORY_SEPARATOR, __FILE__);
define('__CUR_FILE__', $_current_file);
echo __CUR_FILE__;
?>
<?php
$fp = fopen('output.txt', 'r+');
//读取10个字符
echo fread($fp,10);
//指针设置回到开始处
rewind($handle);
//再读取10次看看输出的是什么
echo fread($fp,10);
//文件指针向后移动10个字符
echo fseek($fp,10);
//再看看文件中输出的是什么
echo fread($fp,10);
fclose($handle);
?>
<?php
$filename = 'demo.txt';
echo $filename . '文件大小为: ' . filesize($filename) . ' bytes';
?>
opqrst
uvwxyz
12345678<?php
//以增加的r模式打开
$fp = fopen('demo.txt','r+');
//你分发现每次只读一个字符
echo fgetc($fp);
//我要全部读取可以,读取一次将结果赋值一次给$string
while($string = fgetc($fp)){
echo $string;
}
?>
<?php
//以增加的r模式打开
$fp = fopen('demo.txt','r+');
//你分发现每次只读一个字符
echo fgets($fp);
echo fgets($fp);
echo fgets($fp);
echo fgets($fp);
?>
<?php
//打开我们上面的demo.txt文件
$file = fopen("demo.txt", "a+");
//你可以数数20个字有多长,看看是不是达到效果了
echo ftruncate($file,20);
fclose($file);
?>
<?php
$filename = 'demo.txt';
if (file_exists($filename)) {
echo "$filename文件的上次访问时间是: " . date("Y-m-d H:i:s", fileatime($filename));
echo "$filename文件的创建时间是: " . date("Y-m-d H:i:s", filectime($filename));
echo "$filename文件的修改时间是: " . date("Y-m-d H:i:s", filemtime($filename));
}
?>
Therefore, we introduce the lock mechanism at this time.
If user A writes or reads this file, add the file to the shared location. I can read it, and so can others.
But, if this is the case. I use exclusive lock. This file belongs to me. Don't touch it unless I release the file lock. <?php
$fp = fopen("demo.txt", "r+");
// 进行排它型锁定
if (flock($fp, LOCK_EX)) {
fwrite($fp, "文件这个时候被我独占了哟\n");
// 释放锁定
flock($fp, LOCK_UN);
} else {
echo "锁失败,可能有人在操作,这个时候不能将文件上锁";
}
fclose($fp);
?>
In the above example, in order to write to the file, I added an exclusive lock to the file.
If my operation is completed, after the writing is completed, the exclusive lock is released.
If you are reading a file, you can add a shared lock according to the same processing idea.
##10. Directory processing function
Before, all we processed were files, so how to deal with directories and folders? Let’s learn the functions related to processing directories or folders. The basic idea of processing folders is as follows: Judge whether it is a folder when reading a certain path If it is a folder, open the specified folder and return the file Resource variables of the directoryUse readdir to read the files in the directory once, and the directory pointer is offset backward onceUse readdir to read to the end, if there is no readable file, return falseClose the file directoryLet’s learn a common function:
##<?php
//设置打开的目录是D盘
$dir = "d:/";
//判断是否是文件夹,是文件夹
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
//读取一次向后移动一次文件夹指针
echo readdir($dh).'<br />';
echo readdir($dh).'<br />';
echo readdir($dh).'<br />';
echo readdir($dh).'<br />';
//读取到最后返回false
//关闭文件夹资源
closedir($dh);
}
}
?>
Since it is read once and backward Move once, can we
<?php //设置打开的目录是D盘 $dir = "d:/"; //判断是否是文件夹,是文件夹 if (is_dir($dir)) { if ($dh = opendir($dir)) { //读取到最后返回false,停止循环 while (($file = readdir($dh)) !== false) { echo "文件名为: $file : 文件的类型是: " . filetype($dir . $file) . "<br />"; } closedir($dh); } } ?>
11. File permission settingsFile permission settings The functions are commonly used in system management level software. For example: a certain file is not allowed to be viewed by the guest group (guest users).
In enterprise management, certain users or certain user files are only allowed to be read and not modified. These are very commonly used functions.
Note:
This chapter is an understanding chapter. If you have not learned Linux before and it will be a bit difficult, you can skip this chapter and learn about this thing.
is less useful in actual production processes.
Mainly for students who have a comprehensive knowledge system under Linux and can focus on learning.
Some functions under windows cannot be implemented.
The usage of the above function is the same as that of Linux permission operation.
It is relatively easy for students who have learned Linux. Those who have not learned it will find it a little difficult.
I will only give you an example to see how to modify permissions:
chmod mainly modifies the permissions of files
<?php //修改linux 系统/var/wwwroot/某文件权限为755 chmod("/var/wwwroot/index.html", 755); chmod("/var/wwwroot/index.html", "u+rwx,go+rx"); chmod("/somedir/somefile", 0755); ?>
We often encounter the situation of processing file paths.
For example:
The file suffix needs to be taken out
The path needs to be taken out from the name but not the directory
Only the directory path in the path name needs to be taken out
Or parse each part of the URL to obtain independent values
Or even form a URL yourself
... ....
It is needed in many places Functions of the path processing class.
We have marked the commonly used path processing functions for everyone. You can just process this path processing function:
2.Pathinfo
array pathinfo (string $path)
Function: Pass in the file path and return the various components of the file
We use specific examples to use Take a look:
<?php $path_parts = pathinfo('d:/www/index.inc.php'); echo '文件目录名:'.$path_parts['dirname']."<br />"; echo '文件全名:'.$path_parts['basename']."<br />"; echo '文件扩展名:'.$path_parts['extension']."<br />"; echo '不包含扩展的文件名:'.$path_parts['filename']."<br />"; ?>
The results are as follows:
File directory name: d:/www
Full file name:lib.inc.php
File extension:php
No File name containing extension: lib.inc
3.Basename
string basename (string $path[, string $suffix])
Function : Pass in the path and return the file name
The first parameter is the path passed in.
The second parameter specifies that my file name will stop when it reaches the specified character.
<?php echo "1: ".basename("d:/www/index.d", ".d").PHP_EOL; echo "2: ".basename("d:/www/index.php").PHP_EOL; echo "3: ".basename("d:/www/passwd").PHP_EOL; ?> 4.Dirname dirname(string $路径) 功能:返回文件路径的文件目录部份 <?php dirname(__FILE__); ?>
Conclusion: You can execute it to see if the directory part of the file is returned.
5.parse_url
mixed parse_url (string $path)
Function: Split the URL into various parts
<?php $url = 'http://username:password@hostname:9090/path?arg=value#anchor'; var_dump(parse_url($url)); ?>
The results are as follows:
array(8) {
["scheme"]=> string(4) "http"
["host"]=> string(8 ) "hostname"
["port"]=> int(9090)
["user"]=> string(8) "username"
["pass"]=> string( 8) "password"
["path"]=> string(5) "/path"
["query"]=> string(9) "arg=value"
["fragment "]=> string(6) "anchor"
}
6.http_build_query
string http_build_query (mixed $data to be processed)
Function: Generate the query string in the url
<?php //定义一个关联数组 $data = [ 'username'=>'liwenkai', 'area'=>'hubei' ]; //生成query内容 echo http_build_query($data); ?>
The result is as follows:
username=liwenkai&area=hubei
http_build_url()
Function: Generate a url
Note:
PHP_EOL constant
is equivalent to echo "\r\n" on the windows platform;
is equivalent to the unix\linux platform On the mac platform, it is equivalent to echo "\r";
#13. Text guestbookWe have talked about so many file processing systems, but we can’t even write down the most basic thing.
Starting from this section, you will find that you can write more and more things.
Next let’s take a look at the demonstration effect:
The form interface for writing the message content in the following interface:
The display interface after leaving the message :
Let’s take a look at the file structure:
index.php --- Display the input box and message contentwrite.php ---Write data to message.txtmessage.txt ---Save chat content
index.php file
<?Php //设置时区 date_default_timezone_set('PRC'); //读了内容 @$string = file_get_contents('message.txt'); //如果$string 不为空的时候执行,也就是message.txt中有留言数据 if (!empty($string)) { //每一段留言有一个分格符,但是最后多出了一个&^。因此,我们要将&^删掉 $string = rtrim($string, '&^'); //以&^切成数组 $arr = explode('&^', $string); //将留言内容读取 foreach ($arr as $value) { //将用户名和内容分开 list($username, $content, $time) = explode('$#', $value); echo '用户名为<font color="gree">' . $username . '</font>内容为<font color="red">' . $content . '</font>时间为' . date('Y-m-d H:i:s', $time); echo '<hr />'; } } ?> <h1>基于文件的留言本演示</h1> <form action="write.php" method="post"> 用户名:<input type="text" name="username" /><br /> 留言内容:<textarea name="content"></textarea><br /> <input type="submit" value="提交" /> </form>
After reading the display just now, we know that when the file is stored:
Section is divided between sections
The content and the user are separated using a special symbol
Let’s write write.php code to write messages to files:
<?php //追加方式打开文件 $fp=fopen('message.txt','a'); //设置时间 $time=time(); //得到用户名 $username=trim($_POST['username']); //得到内容 $content=trim($_POST['content']); //组合写入的字符串:内容和用户之间分开,使用$# //行与行之间分开,使用&^ $string=$username.'$#'.$content.'$#'.$time.'&^'; //写入文件 fwrite($fp,$string); //关闭文件 fclose($fp); header('location:index.php'); ?>