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.
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.
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.
'; } ?>
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 functionThe 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 functionThe 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
2.Read the file
3. Close the file
Other notes: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
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.
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:
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.
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: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 filesThe 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.
##
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:
You will find that there is an extra file through the above example.
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)
Function: whether the file exists.
bool is_readable ($specifies the file name or file path)
Function: whether the file is readable
bool is_writeable ($specifies the file name or file path)
Function: whether the file is writable
bool is_executable ($specifies the file name or file path)
Function: whether the file is executable
bool is_file ($specifies the file name or file path)
Function: whether it is a file
bool is_dir ($specifies the file name or file path)
Function: Whether it is a directory
void clearstatcache (void)
Function: Clear the status cache of the file
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.
不可读'; } if(is_writeable($v)){ echo '可写'; }else{ echo '不可写'; } echo '
'; } if($flag){ echo '下一步'; }else{ echo '不能进行安装'; } ?>
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
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.
We will use a constant:
DIRECTORY_SEPARATOR
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.
Then don’t use FILE. You can use custom constants and process FILE as follows:
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
- Abcdeefghijklk
- Opqrst ##Uvwxyz
- ## 12345678
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
opqrst
uvwxyz
12345678
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
The file lock mechanism generally has no effect at all when a single file is opened. This part of learning is a little abstract. Don’t think about how to achieve it? Why can’t I see the effect?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.
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.
Note: Regardless of whether the file lock is added, be careful to release it.
Let’s take a look at this function:bool flock ( resource $handle , int $operation)
Function: Light consultation file locking
Let’s take a look at the lock type: We will add an exclusive lock to demo.txt and proceed write operation. Description: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 directory Use readdir to read the files in the directory once, and the directory pointer is offset backward once Use readdir to read to the end, if there is no readable file, return false Close the file directory Let’s learn a common function:##
'; echo readdir($dh).'Since it is read once and backward Move once, can we
'; echo readdir($dh).'
'; echo readdir($dh).'
'; //读取到最后返回false //关闭文件夹资源 closedir($dh); } } ?>
"; } 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
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:
"; echo '文件全名:'.$path_parts['basename']."
"; echo '文件扩展名:'.$path_parts['extension']."
"; echo '不包含扩展的文件名:'.$path_parts['filename']."
"; ?>
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.
4.Dirname dirname(string $路径) 功能:返回文件路径的文件目录部份
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
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
'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
' . $username . '内容为' . $content . '时间为' . date('Y-m-d H:i:s', $time); echo '
'; } } ?>基于文件的留言本演示
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: