PHP file handling
PHP has a variety of functions for creating, reading, uploading, and editing files.
Attention: Please handle files with caution!
You must be very careful when you manipulate files. If you do it incorrectly, you can cause very serious damage.
Common mistakes are:
1. Edit the wrong file
2. Fill the hard drive with junk data
3. Accidental deletion of file content
PHP readfile() function
readfile($file name)
Function: Pass in a file path and output a file
For example, there is a file named file.txt with the following content
Welcome in the PHP Chinese learning PHP
Use The PHP code for the readfile() function to read this file and write it to the output stream is as follows (if the read is successful, the readfile() function returns the number of bytes):
Number of bytes: English Occupies one byte, gbk encoded Chinese occupies 2 utf-8 Chinese occupies 3 byte, spaces and symbols occupy 1 byte
<?php echo readfile("D:WWW/item/file.txt"); ?>
Program operation result:
Welcome in the PHP Chinese learning PHP39
file_get_contentsOpen the file
above Just open the file and it will be output directly. Is there any operation method that can be assigned to a variable after opening the file?
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:
file_get_contents (string filename)
Function: Pass in a file or file path, open the file and return the contents of the file. The content of the file is a string.
For example, there is a file.txt file with the following content:
I use the file_get_contents open
Use file_get_contents to open
<?php $fileName="file.txt"; $filestring = file_get_contents($fileName); echo $filestring; ?>
Program running result:
I use the file_get_contents open
fopen, fread, fclose operations read files
# #fopen ($file name, mode)
fread ($operation resource, read length)
fclose ($Operation Resource)
Through the above function, we will explain the usual operation methods of resource types:1. Open the resource2. Use related functions to operate3. Close the resource
fopenThe function of the fopen function is to open a file. There are two main parameters:
1. The path to open the file 2. The mode to open the file The resource type requires other functions. 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.
fcloseFunction The function of the fclose function is to close resources. Resources are opened and closed.
fopen mode (table below):
rRead only. Start at the beginning of the file. r+Read/write. Start at the beginning of the file. Write only. Opens and clears the contents of the file; if the file does not exist, creates a new file.Mode | Description |
w+ | read/write. Opens and clears the contents of the file; if the file does not exist, creates a new file. |
## a | |
Read/Append. Maintain file contents by writing to the end of the file. | |
x Write only. Create new file. If the file already exists, returns FALSE and an error. | |
x+ read/write. Create new file. If the file already exists, returns FALSE and an error. | |
Convert \n to \r\n |
1. Open the file
file.txt The contents of the file are as follows
You're welcome
<?php //你可以创建一个file.txt,以只读模式打开 $fp = fopen('file.txt', "r"); //var_dump()操作一下$fp看看效果,输出的是不是只有类型提示的是resource var_dump($fp); ?>
2. Read the file
<?php $fp = fopen('file.txt', "r"); //打开一个文件类型后,读取12个字节 $contents = fread($fp, 12); ?>
3. Close the file
<?php $fp = fopen('file.txt', 'r'); $contents = fread($fp, 1024); fclose($fp); echo $contents; ?>
Program running result:
You're welcome
file_put_contents and fwrite write files
file_put_contents (string $file path, string $write data])
Function: Write to the specified file A string to create the file if it does not exist. Returns the length of written bytes
Example
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $data = "我是一个兵,来自老百姓"; $numbytes = file_put_contents('binggege.txt', $data); if($numbytes){ echo '写入成功,我们读取看看结果试试:'; echo file_get_contents('binggege.txt'); }else{ echo '写入失败或者没有权限,注意检查'; } ?>
The program running result:
The writing is successful, let’s read and see the result: I am a soldier, from the common people
fwrite ( resource $file resource variable, string $written string[, int length ])
Note: The alias function of fwrite is fputs
We tried the r mode above, and it was only used when reading. Next, we use fwrite to add Use w in fopen to write files in write mode
Example
You can try creating a new test.txt file and write content into it. Then, you can try to delete test.txt. See what tips there are.
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $filename = 'test.txt'; $fp= fopen($filename, "w"); $len = fwrite($fp, '我是一只来自南方的狼,一直在寻找心中的花姑娘'); fclose($fp); print $len ."字节被写入了\n"; ?>
Program running result:
66 bytes were written
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. If the file does not exist, it will be created
Compare the differences between the following modes:
Example
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $filename = 'test.txt'; $fp= fopen($filename, "r"); $len = fwrite($fp, '我是一只来自南方的狼,一直在寻找心中的花姑娘'); fclose($fp); print $len .'字节被写入了\n'; ?>
Program running result:
0 bytes are written Enter\n
We found that writing using only r was unsuccessful
Creating 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 them after use
2. There is no need to maintain the deletion status of this file
For example: I need to delete A’s Transfer the file contents 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.
Example
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $handle = tmpfile(); //向里面写入了数据 $numbytes = fwrite($handle, '写入临时文件的内容'); //关闭临时文件,文件即被删除 fclose($handle); echo '向临时文件中写入了'.$numbytes . '个字节'; ?>
Program running result:
Write to temporary file Entered 27 bytes
Move, copy, delete files
Rename file
rename($old name,$new name);
This function returns a bool value and changes the old name to the new name.
Example
<?php $fileName1="text.txt"; $fileName2="text--1.txt"; rename($fileName1,$fileName2); ?>
The above example is to rename a text.txt file to text--1.txt. You might as well You can try
Copy the file
copy(Source File, target file)
Function: Copy the source file with the specified path to the location of the target file.
Example
<?php $filename = 'file.txt'; //旧文件名 $filename2 = 'copy-file.txt'; //新文件名 copy($filename, $filename2); //修改名字。 ?>
##The above example is to name a file file.txt file, copy a file named copy-file.txt with the same content.
Delete file
unlink (File with specified path)
Example
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $filename = 'test.txt'; unlink($filename); ?>
The above example is to delete a file named test.txt
Functions commonly used in files
filesize Detect file size
Example
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $filename = 'file.txt'; echo $filename . '文件大小为: ' . filesize($filename) . ' bytes'; ?>
Program running result:
file.txt file size is: 14 bytes
Other functions for operating files, reading files
Mode | ## Description |
Can both read and write |
Function name | Function |
file | Read the entire file into an array |
fgets | Read a line from the file pointer, read Finally returns false |
fgetc | Reads a character from the file pointer, and returns false |
after reading it at the end ftruncate | Truncate file to given length |
#We use an example to use all the above functions.
We write a batch of files in the text.txt file:
abcdeefghijklk
opqrst
uvwxyz
12345678
##fgetc reads one
<?php //以增加的r模式打开 $fp = fopen('text.txt','r+'); //你分发现每次只读一个字符 echo fgetc($fp) ."<br>"; //我要全部读取可以,读取一次将结果赋值一次给$string while($string = fgetc($fp)){ echo $string; } ?>each time the program runs:
a bcdeefghijklk opqrst uvwxyz 12345678
##fgets opens one line at a time:
<?php //以增加的r模式打开 $fp = fopen('text.txt','r+'); //你分发现每次只读一个字符 echo fgets($fp)."<br>"; echo fgets($fp)."<br>"; echo fgets($fp)."<br>"; echo fgets($fp); ?>Program running results :abcdeefghijklk
opqrstuvwxyz
12345678
##File interception function
<?php //打开我们上面的text.txt文件 $file = fopen("text.txt", "a+"); //你可以数数20个字有多长,看看是不是达到效果了 echo ftruncate($file,10); fclose($file); ?>
Run the program, you can open the text.txt file and see if there are 20 bytes
Time function of file
## Function File creation time filemtime File modification time fileatime File last access time
Example
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $filename = 'text.txt'; if (file_exists($filename)) { echo "$filename"."文件的上次访问时间是: " . date("Y-m-d H:i:s", fileatime($filename))."<br>"; echo "$filename"."文件的创建时间是: " . date("Y-m-d H:i:s", filectime($filename))."<br>"; echo "$filename"."文件的修改时间是: " . date("Y-m-d H:i:s", filemtime($filename)); } ?>
Program running result:
Last access to text.txt file The time is: 2016-09-13 17:44:40
The creation time of the text.txt file is: 2016-09-13 17:32:16
The modification time of the text.txt file is: 2016-09 -13 17:44:55
Directory processing function
Before we processed all files, then the directory How to deal with folders?
Let’s learn the functions related to the processing of directories or folders.
The basic idea of processing folders is as follows:
1. Read a certain When specifying the path, determine whether it is a folder
2. If it is a folder, open the specified folder and return the resource variable of the file directory
3. Use readdir to read the files in the directory once. The directory pointer is shifted backward once
4. Use readdir to read to the end. If there is no readable file, return false
5. Close the file directory
Let’s learn about it More commonly used functions:
Function description | ## filectime |
Function name | Function |
opendir | Open the folder and return to the operation resource |
readdir | Read folder resources |
Filetype | displays whether it is a folder or a file. The file displays file and the folder displays dir |
Example
<?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 />'; echo readdir($dh).'<br />'; echo readdir($dh).'<br />'; //读取到最后返回false //关闭文件夹资源 closedir($dh); } } ?>
You can run the program to see if it is you Directory of computer D drive
Determine the type of file
<?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); } } ?>
Run Take a look at the program
File path function
We often encounter the situation of processing file paths.
For example:
1. The file suffix needs to be taken out
2. The path needs to be taken out from the name and not the directory
3. You only need to take out the directory path in the path name
4. Or parse each part of the URL to obtain independent values
5. Or even form a URL by yourself Come out
You need to use path processing class functions in many places.
We have marked the commonly used path processing functions for everyone. You can just process this path processing function:
Function name | Function |
pathinfo | Return file Each component of |
basename | return file name |
dirname | file directory part |
parse_url | The URL is broken down into its parts |
http_build_query | Generate the query string in the url |
http_build_url | Generate a url |
pathinfo
pathinfo (string $path)
Function: Pass in the file path and return each Component
Example
<?php header("Content-type:text/html;charset=utf-8"); $path_parts = pathinfo('D:/www/a.html'); echo '文件目录名:'.$path_parts['dirname']."<br />"; echo '文件全名:'.$path_parts['basename']."<br />"; echo '文件扩展名:'.$path_parts['extension']."<br />"; echo '不包含扩展的文件名:'.$path_parts['filename']."<br />"; ?>
Program running result:
File directory name: D:/www
Full file name: a.html
File extension: html
File name without extension: a
basename
basename ( string $path[, string $suffix])
Function: Pass in the path and return the file name
The first parameter is passed in the path.
The second parameter specifies that my file name will stop when it reaches the specified character.
Example
<?php echo "1: ".basename("d:/www/a.html", ".d")."<br>"; echo "2: ".basename("d:/www/include")."<br>"; echo "3: ".basename("d:/www/text.txt")."<br>"; ?>
Program running result:
1: a.html
2: include
3: text.txt
dirname
##dirname(string $path ) Function: Return the file directory part of the file path
Example
<?php $a=dirname(__FILE__); echo$a; ?>
Run your program
parse_url
##parse_url(string $path) Function: Split the URL into various parts
Example
<?php $url = 'http://username:password@hostname:9090/path?arg=value#anchor'; var_dump(parse_url($url)); ?>Program running result: 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"
}
##http_build_query
http_build_query
(mixed $Data to be processed)Function: Generate query string in url
Example
<?php //定义一个关联数组 $data = [ 'username'=>'liwenkai', 'area'=>'hubei', 'pwd'=>'123' ]; //生成query内容 echo http_build_query($data); ?>
Program running result:
username= liwenkai&area=hubei&pwd=123
#PHP Filesystem Reference Manual