Home Backend Development PHP Tutorial Introduction to commonly used file operation functions in php_PHP tutorial

Introduction to commonly used file operation functions in php_PHP tutorial

Jul 13, 2016 pm 05:15 PM
php introduce Instructions function beginner Commonly used operate document of

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
 代码如下 复制代码

/* 判断post.php是否存在 */
$file="post.php";
if(file_exists($file)){
echo "文件存在
";
 }
 else{
  echo "文件不存在
";
 }
 
 /* 判断images目录是否存在 */
 $category="images";
 if(file_exists($category)){
  echo "目录存在";
 }
 else{
  echo "目录不存在";
 } 
?>

/* Determine whether post.php exists */
$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";
}
?>

php provides some functions for accessing file attributes, which can obtain the file size, type, modification time, etc.

获取文件属性函数

函数名 作用 参数及返回值
filesize($string) 获取文件大小 参数$string为一个指向文件或目录的字符型变量。函数的返回值为整型变量,返回文件的大小,返回结果会被缓存。如果出错,则返回false。函数参数不能为远程文件。
filetype($string) 获取文件类型 参数$string为一个指向文件或目录的字符型变量。函数的返回值为字符型变量,返回结果会被缓存。
filemtime($string) 获取文件修改时间 参数$string为一个指向文件或目录的字符型变量。函数的返回值为整型变量,返回文件的修改时间。
fileatime($string) 获取文件访问时间 参数$string为一个指向文件或目录的字符型变量。函数的返回值为整型变量,返回文件的访问时间。
fileperms($string) 获取文件权限 参数$string为一个指向文件或目录的字符型变量。函数的返回值为整型变量,返回文件的相应权限,返回结果会被缓存。函数参数不能为远程文件。

Get file attribute function

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";
 echo filesize($filename). "
";
 echo filetype($filename). "
";
 echo date("Y年 m月 d日",filemtime($filename)). "
";
 echo date("Y年 m月 d日",fileatime($filename)). "
";
 echo fileperms($filename). "
";
?>

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:

Description of mode parameter in fopen()
fopen()中的mode参数说明
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 以及以后的版本所支持,仅能用于本地文件。
mode Description
r Open in read-only mode and point the file pointer to the file header.
r+ Open in read-write mode and point the file pointer to the file header.
w Open in writing mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it.
w+ Open in read-write mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it.
a Open in writing mode and point the file pointer to the end of the file. If the file does not exist, try to create it.
a+ Open in read-write mode and point the file pointer to the end of the file. If the file does not exist, try to create it.
x is created and opened for writing, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE and generates an E_WARNING level error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL|O_CREAT flag for the underlying open(2) system call. This option is supported by PHP 4.3.2 and later, and can only be used for local files.
x+ is created and opened for reading and writing, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE and generates an E_WARNING level error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL|O_CREAT flag for the underlying open(2) system call. This option is supported by PHP 4.3.2 and later, and can only be used for local files.

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"); /* 写入方式打开本地文件 */
fopen("http://www.bKjia.c0m/robots.txt","r"); /* 只读方式打开远程服务器文件 */
?>

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');
$string=fgetc($filename); /* 读取文件开头第一个字符 */
echo $string;
?>

 

The parameter $handle is the file pointer that has been opened, and the function returns the character pointed to by the current file pointer. If the file pointer points to the end of the file, returns false. Example:
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
 代码如下 复制代码

$f=fopen("php.txt","r");
fgets($f,2);
echo ftell($f);
?>

Copy code

$f=fopen("php.txt","r");

fgets($f,2);

echo ftell($f);

?>

 代码如下 复制代码

 $filename="php.txt";
 $str1="第一次写入
";
 $str2="第二次写入";
 if(is_writable($filename)){  /* is_writable()函数判断文件是否可写 */
  $file=fopen($filename,"w"); /* 以写入方式打开文件 */
  $w1=fwrite($file,$str1); /* 将内容写入文件 */
  $w2=fwrite($file,$str2);
   $file=fopen($filename,"r"); 
   if($w1) echo fgets($file); /* 读取文件内容 */
   else echo "写入不成功"; 
 }
 else echo "文件不可写";
?>


php file writing function fwrite() can write the required content into the target file. The structure is as follows:


int fwrite(resource $handle,string $string [,int $length])

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:

The code is as follows
 代码如下 复制代码

 $f=fopen("php.txt","r");
 echo fgets($f)."
";  /*输出第一行*/
 echo fgets($f)."
";  /*输出第二行*/
 rewind($f);             /*指针返回文件头*/
 echo fgets($f);         /*输出第一行*/   
?>

Copy code
$str1="First write
";

$str2="Second write"; $file=fopen($filename,"w"); /* Open the file for writing */ $w1=fwrite($file,$str1); /* Write the content to the file */ $w2=fwrite($file,$str2); $file=fopen($filename,"r"); If($w1) echo fgets($file); /* Read file content */ else echo "Write failed"; } else echo "File cannot be written"; ?>
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:
The code is as follows Copy code
"; /*Output the first line*/ echo fgets($f)."
"; /*Output the second line*/ rewind($f); /*The pointer returns the file header*/ echo fgets($f); /*Output the first line*/ ?> http://www.bkjia.com/PHPjc/628845.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628845.htmlTechArticleThe editor today will introduce to PHP beginners a summary of the common functions used for PHP file operations, including: file reading and writing , create, view file attributes, file deletion and other operations on files. ...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

Using Laravel: Streamlining Web Development with PHP Using Laravel: Streamlining Web Development with PHP Apr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

PHP and IIS: Making Them Work Together PHP and IIS: Making Them Work Together Apr 21, 2025 am 12:06 AM

Configuring and running PHP on IIS requires the following steps: 1) Download and install PHP, 2) Configuring IIS and adding FastCGI module, 3) Create and set up an application pool, 4) Create a website and bind to an application pool. Through these steps, you can easily deploy PHP applications on your Windows server and improve application stability and efficiency by configuring scaling and optimizing performance.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

See all articles