


Introduction to commonly used file operation functions in php_PHP tutorial
Today, the editor will introduce to PHP beginners a summary of the common functions used in PHP file operations, including: file reading and writing, creation, viewing file attributes, file deletion and other file operations.
Before accessing a file, we generally need to determine whether the file exists to avoid calling a non-existent file and causing an error.
PHP function to determine whether a file exists: file_exists(), the structure is as follows:
file_exist($string);
The parameter $string is a character variable pointing to a file or directory. If the file or directory exists, it returns true, otherwise it returns false.
Example:
The code is as follows | Copy code | ||||
$file="post.php"; if(file_exists($file)){ echo "File exists "; } else{ echo "File does not exist "; } /* Determine whether the images directory exists */ $category="images"; if(file_exists($category)){ echo "Directory exists"; } else{ echo "Directory does not exist"; } ?>
|
函数名 | 作用 | 参数及返回值 |
---|---|---|
filesize($string) | 获取文件大小 | 参数$string为一个指向文件或目录的字符型变量。函数的返回值为整型变量,返回文件的大小,返回结果会被缓存。如果出错,则返回false。函数参数不能为远程文件。 |
filetype($string) | 获取文件类型 | 参数$string为一个指向文件或目录的字符型变量。函数的返回值为字符型变量,返回结果会被缓存。 |
filemtime($string) | 获取文件修改时间 | 参数$string为一个指向文件或目录的字符型变量。函数的返回值为整型变量,返回文件的修改时间。 |
fileatime($string) | 获取文件访问时间 | 参数$string为一个指向文件或目录的字符型变量。函数的返回值为整型变量,返回文件的访问时间。 |
fileperms($string) | 获取文件权限 | 参数$string为一个指向文件或目录的字符型变量。函数的返回值为整型变量,返回文件的相应权限,返回结果会被缓存。函数参数不能为远程文件。 |
Function name | Function | Parameters and return values |
---|---|---|
filesize($string) | Get file size | The parameter $string is a character type variable that points to a file or directory. The return value of the function is an integer variable, returning the size of the file, and the return result will be cached. If an error occurs, false is returned. Function parameters cannot be remote files. |
filetype($string) | Get file type | The parameter $string is a character variable pointing to a file or directory. The return value of the function is a character variable, and the return result will be cached. |
filemtime($string) | Get file modification time | The parameter $string is a character variable pointing to a file or directory. The return value of the function is an integer variable and returns the modification time of the file. |
fileatime($string) | Get file access time | The parameter $string is a character variable pointing to a file or directory. The return value of the function is an integer variable and returns the access time of the file. |
fileperms($string) | Get file permissions | The parameter $string is a character variable pointing to a file or directory. The return value of the function is an integer variable and returns the corresponding permissions of the file. The return result will be cached. Function parameters cannot be remote files. |
Example:
代码如下 | 复制代码 |
$filename="php.txt"; |
The code is as follows | Copy code |
$filename="php.txt"; echo filesize($filename). " "; echo filetype($filename). " "; echo date("Y year m month d day",filemtime($filename)). " "; echo date("Y year m month d day",fileatime($filename)). " "; echo fileperms($filename). " "; ?> |
Before reading a file, you must first open a file. PHP provides the fopen() function to open local files or remote files. Its basic structural form is as follows:
resource fopen (string $filename, string $mode)
The parameter filename is the name of the file to be opened. The parameter mode is the way to open the file, as shown in the following table:
mode | 说明 |
---|---|
r | 只读方式打开,将文件指针指向文件头。 |
r+ | 读写方式打开,将文件指针指向文件头。 |
w | 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 |
w+ | 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 |
a | 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 |
a+ | 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 |
x | 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 |
x+ | 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 |
The fopen() function returns a value that contains an integer file handle and is used to identify the file to the function that performs the file operation. This value is often called a pointer, which is like a door to a room in memory. If php fails to open the file, then this value is false.
Example:
The code is as follows | Copy code | ||||
fopen("php.txt","a"); /* Open local file in writing mode */ fopen("http://www.bKjia.c0m/robots.txt","r"); /* Open the remote server file in read-only mode */
?> |
First create a "php.txt" file with the following content:
hello
php
1. The fgetc() function reads a certain character in the file. Its structure is as follows:
string fgetc(resource $handle)
代码如下 | 复制代码 |
$filename=fopen('php.txt','r');
|
The code is as follows | Copy code |
$filename=fopen('php.txt','r'); $string=fgetc($filename); /* Read the first character at the beginning of the file */ echo $string; ?> |
After the file is opened, the file pointer is usually located at the beginning of the file. But when certain operations are performed on the file, it is difficult to determine the position of the php pointer at this time.
php file pointer position search function ftell(), its structure is as follows:
int ftell(resource $handle)
The parameter $handle is the file where the pointer is to be found. This function can determine the position of the file pointer, and the function returns an integer value.
Example:
The code is as follows
|
Copy code
|
||||||||||||||||
$f=fopen("php.txt","r"); fgets($f,2);echo ftell($f); ?>
The parameter $handle is the file to be written, the adopted number $string is the content to be written, and the parameter $length is optional and is the length to be written. The fwrite() function returns the number of characters written, and returns false if an error occurs. Example:
$str1="First write
The PHP pointer function rewind() can set the file location pointer to the beginning of the file. Its structure is as follows:
bool rewind (resource $handle );
The function returns a Boolean value, true if successful, false if failed.
Example:
|

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
