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):
Mode | Description |
Read only. Start at the beginning of the file. | |
Read/write. Start at the beginning of the file. | |
w+ | read/write. Opens and clears the contents of the file; if the file does not exist, creates a new file. |
## a | Append. Opens and writes to the end of the file, or creates a new file if it does not exist.|
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 |
Mode | ## Description | |||||||||||||||||||||||||
Can only be read and cannot be written using fwrite | ||||||||||||||||||||||||||
Can be read and written | ||||||||||||||||||||||||||
Can only write function | ||||||||||||||||||||||||||
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 :
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 description | ## filectime | File creation time|||||||||||||||||||||||||
filemtime | File modification time | |||||||||||||||||||||||||
fileatime | File last access time | |||||||||||||||||||||||||
Function name | Function |
opendir | Open the folder and return to the operation resource |
readdir | Read folder resources |
Determine whether it is a folder | |
Close folder operation 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:
["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 Program running result: username= liwenkai&area=hubei&pwd=123 #PHP Filesystem Reference Manual Students who have watched this course are also learning<?php
//定义一个关联数组
$data = [
'username'=>'liwenkai',
'area'=>'hubei',
'pwd'=>'123'
];
//生成query内容
echo http_build_query($data);
?>
ElementaryImperial CMS enterprise imitation website tutorial
ElementaryNewbies with zero foundation in WordPress build personal blogs and corporate websites
ElementaryUltimate CMS zero-based website building instruction video
ElementaryFront-end project-Shangyou [HTML/CSS/JS technology comprehensive practice]
IntermediateVue3.0 from 0 to build a universal backend management system project practice
ElementaryZero-based front-end course [Vue advanced learning and practical application]
ElementaryWEB front-end tutorial [HTML5+CSS3+JS]
ElementaryQuick introduction to apipost
IntermediateVue3+TypeScript practical tutorial-enterprise-level project practice
ElementaryLet's briefly talk about starting a business in PHP
IntermediateVUE e-commerce project (front-end & back-end dual project actual combat)
ElementaryApipost practical application [api, interface, automated testing, mock]