PHP 基础
PHP 简介
PHP 入门
PHP 语法
PHP 变量
PHP 常量
PHP 输出和打印
PHP 数据类型
PHP 字符串
PHP 运算符
PHP If…Else
PHP Switch…Case
PHP 数组
PHP 数组排序
PHP 循环
PHP 函数
PHP 数学运算
PHP GET 和 POST
PHP 高级
PHP 日期和时间
PHP 包含文件
PHP 文件系统
PHP 解析目录
PHP 文件上传
PHP 文件下载
PHP Cookies
PHP Sessions
PHP 发送邮件
PHP 表单处理
PHP 表单验证
PHP 过滤器
PHP 错误处理
PHP 类和对象
PHP 魔术常量
PHP JSON 解析
PHP 正则表达式
PHP 异常处理
PHP 和 MySQL 数据库
PHP MySQL 简介
PHP MySQL 连接
PHP MySQL Create Database
PHP MySQL Create Table
PHP MySQL Insert
PHP MySQL Prepared
PHP MySQL Last Inserted ID
PHP MySQL Select
PHP MySQL Where
PHP MySQL Limit
PHP MySQL Order By
PHP MySQL Update
PHP MySQL Delete
PHP MySQL CRUD 应用
PHP MySQL Ajax 搜索
PHP MySQL 登录系统
PHP参考
PHP String Functions
PHP Array Functions
PHP File System Functions
PHP Date/Time Functions
PHP Calendar Functions
PHP MySQLi Functions
PHP Filters
PHP Error Levels
PHP常见问题解答
如何在 PHP 中编写注释
如何在 PHP 中删除字符串中的空格
如何在 PHP 中查找字符串中的字符数
如何在 PHP 中查找字符串中的单词数
如何在 PHP 中删除字符串中的特殊字符
如何在 PHP 中替换字符串中的一个单词
如何在 PHP 中对字符串前面追加
如何在 PHP 中对字符串后面追加
如何在 PHP 中从字符串中提取子串
如何在 PHP 中比较两个字符串
如何在 PHP 中获取当前页面的 URL
如何在 PHP 中通过连接数组值创建字符串
如何在 PHP 中将字符串拆分为数组
如何在 PHP 中合并两个字符串
如何在 PHP 中把字符串转换成小写字母
如何在 PHP 中把字符串转换成大写字母
如何在 PHP 中把字符串的第一个字母转换成大写字母
如何在 PHP 中把特殊的 HTML 实体转换回字符
如何在 PHP 中删除字符串开头的空格
如何在 PHP 中删除字符串结尾的空格
如何在 PHP 中新建一行
如何在 PHP 中查找字符串长度
如何在 PHP 中检查变量是否已设置
如何在 PHP 中检查变量是否为空
如何在 PHP 中检查变量是否为NULL
如何在 PHP 中反转字符串
如何在 PHP 中用另一个字符串替换字符串的一部分
如何在 PHP 中计算子串在字符串中出现的次数
如何在 PHP 中计算数组中的所有元素
如何在 PHP 中打印或回显数组的所有值
如何在 PHP 中显示数组的结构和值
如何在 PHP 中颠倒数组的顺序
如何在 PHP 中检查数组中是否存在值
如何在 PHP 中检查数组中是否存在键
如何在 PHP 中删除数组中的最后一个元素
如何从 PHP 数组中删除第一个元素
如何在 PHP 中为数组的开头添加元素
如何在 PHP 中为数组的末尾添加元素
如何在 PHP 中把两个或多个数组合并成一个数组
如何在 PHP 中按字母顺序对数组值排序
如何在 PHP 中删除数组中的重复值
如何在 PHP 中随机调整数组的顺序
如何在 PHP 中比较两个数组的值
如何在 PHP 中计算数组中数值的总和
如何在 PHP 中删除数组中的空值
如何在 PHP 中用数组值填充下拉列表
如何在 PHP 中获取关联数组的所有键值
如何在 PHP 中获取关联数组的所有值
如何在 PHP 中按键对关联数组排序
如何在 PHP 中按值对关联数组排序
如何在 PHP 中从数组中获取单个值
如何在 PHP 中循环浏览多维数组
如何在 PHP 中从数组中删除元素
如何在 PHP 中检查字符串是否包含特定单词
如何在 PHP 中获取当前日期和时间
如何在 PHP 中进行重定向
如何在 PHP 中删除字符串中的所有空格
如何用 PHP 获取当前年份
如何在 PHP 中将日期从 yyyy-mm-dd 转换为 dd-mm-yyyy 格式
如何在 PHP 中将字符串转换为数字
如何在 PHP 中获取数组的第一个元素
如何在 PHP 中将日期转换为时间戳
如何在 PHP 中为空数组添加元素
如何在 PHP 中把整数转换成字符串
如何用值而不是键删除 PHP 数组元素
如何在 PHP 中将键和值同时推入数组
如何使用 PHP 定期刷新页面
如何从 PHP 字符串中删除最后一个字符
如何从 PHP 脚本返回 JSON
如何让 PHP 显示错误
PHP 文件系统 - php7基础教程 - 笔下光年
网站首页
PHP 文件系统
In this tutorial you will learn how to create, access (or read) and manipulate files dynamically using the PHP's file system functions. ## Working with Files in PHP Since PHP is a server side programming language, it allows you to work with files and directories stored on the web server. In this tutorial you will learn how to create, access, and manipulate files on your web server using the PHP file system functions. ## Opening a File with PHP fopen() Function To work with a file you first need to open the file. The PHP `fopen()` function is used to open a file. The basic syntax of this function can be given with: ```php fopen(filename, mode) ``` The first parameter passed to fopen() specifies the name of the file you want to open, and the second parameter specifies in which mode the file should be opened. For example: ```php <?php $handle = fopen("data.txt", "r"); ?> ``` The file may be opened in one of the following modes: | Modes | What it does | |-------|-------------------------------------| | r | Open the file for reading only. | | r+ | Open the file for reading and writing. | | w | Open the file for writing only and clears the contents of file. If the file does not exist, PHP will attempt to create it. | | w+ | Open the file for reading and writing and clears the contents of file. If the file does not exist, PHP will attempt to create it. | | a | Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it. | | a+ | Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it. | | x | Open the file for writing only. Return FALSE and generates an error if the file already exists. If the file does not exist, PHP will attempt to create it. | | x+ | Open the file for reading and writing; otherwise it has the same behavior as 'x'. | If you try to open a file that doesn't exist, PHP will generate a warning message. So, to avoid these error messages you should always implement a simple check whether a file or directory exists or not before trying to access it, with the PHP `file_exists()` function. ```php <?php $file = "data.txt"; // Check the existence of file if(file_exists($file)){ // Attempt to open the file $handle = fopen($file, "r"); } else{ echo "ERROR: File does not exist."; } ?> ``` <div class="callout callout-success mb-3">Tip: Operations on files and directories are prone to errors. So it's a good practice to implement some form of error checking so that if an error occurs your script will handle the error gracefully. See the tutorial on PHP error handling.</div> ## Closing a File with PHP fclose() Function Once you've finished working with a file, it needs to be closed. The `fclose()` function is used to close the file, as shown in the following example: ```php <?php $file = "data.txt"; // Check the existence of file if(file_exists($file)){ // Open the file for reading $handle = fopen($file, "r") or die("ERROR: Cannot open the file."); /* Some code to be executed */ // Closing the file handle fclose($handle); } else{ echo "ERROR: File does not exist."; } ?> ``` <div class="callout callout-info mb-3">Note: Although PHP automatically closes all open files when script terminates, but it's a good practice to close a file after performing all the operations.</div> ## Reading from Files with PHP fread() Function Now that you have understood how to open and close files. In the following section you will learn how to read data from a file. PHP has several functions for reading data from a file. You can read from just one character to the entire file with a single operation. ### Reading Fixed Number of Characters The `fread()` function can be used to read a specified number of characters from a file. The basic syntax of this function can be given with. ```php fread(file handle, length in bytes) ``` This function takes two parameter — A file handle and the number of bytes to read. The following example reads 20 bytes from the "data.txt" file including spaces. Let's suppose the file "data.txt" contains a paragraph of text "The quick brown fox jumps over the lazy dog." ```php <?php $file = "data.txt"; // Check the existence of file if(file_exists($file)){ // Open the file for reading $handle = fopen($file, "r") or die("ERROR: Cannot open the file."); // Read fixed number of bytes from the file $content = fread($handle, "20"); // Closing the file handle fclose($handle); // Display the file content echo $content; } else{ echo "ERROR: File does not exist."; } ?> ``` The above example will produce the following output: ``` The quick brown fox ``` ### Reading the Entire Contents of a File The `fread()` function can be used in conjugation with the `filesize()` function to read the entire file at once. The `filesize()` function returns the size of the file in bytes. ```php <?php $file = "data.txt"; // Check the existence of file if(file_exists($file)){ // Open the file for reading $handle = fopen($file, "r") or die("ERROR: Cannot open the file."); // Reading the entire file $content = fread($handle, filesize($file)); // Closing the file handle fclose($handle); // Display the file content echo $content; } else{ echo "ERROR: File does not exist."; } ?> ``` The above example will produce the following output: ``` The quick brown fox jumps over the lazy dog. ``` The easiest way to read the entire contents of a file in PHP is with the readfile() function. This function allows you to read the contents of a file without needing to open it. The following example will generate the same output as above example: ```php <?php $file = "data.txt"; // Check the existence of file if(file_exists($file)){ // Reads and outputs the entire file readfile($file) or die("ERROR: Cannot open the file."); } else{ echo "ERROR: File does not exist."; } ?> ``` The above example will produce the following output: ``` The quick brown fox jumps over the lazy dog. ``` Another way to read the whole contents of a file without needing to open it is with the `file_get_contents()` function. This function accepts the name and path to a file, and reads the entire file into a string variable. Here's an example: ```php <?php $file = "data.txt"; // Check the existence of file if(file_exists($file)){ // Reading the entire file into a string $content = file_get_contents($file) or die("ERROR: Cannot open the file."); // Display the file content echo $content; } else{ echo "ERROR: File does not exist."; } ?> ``` One more method of reading the whole data from a file is the PHP's `file()` function. It does a similar job to `file_get_contents()` function, but it returns the file contents as an array of lines, rather than a single string. Each element of the returned array corresponds to a line in the file. To process the file data, you need to iterate over the array using a [foreach loop](http://www.bixiaguangnian.com/manual/php7/3976.html#h2-php-foreach-loop "foreach loop"). Here's an example, which reads a file into an array and then displays it using the loop: ```php <?php $file = "data.txt"; // Check the existence of file if(file_exists($file)){ // Reading the entire file into an array $arr = file($file) or die("ERROR: Cannot open the file."); foreach($arr as $line){ echo $line; } } else{ echo "ERROR: File does not exist."; } ?> ``` ## Writing the Files Using PHP fwrite() Function Similarly, you can write data to a file or append to an existing file using the PHP fwrite() function. The basic syntax of this function can be given with: ```php fwrite(file handle, string) ``` The `fwrite()` function takes two parameter — A file handle and the string of data that is to be written, as demonstrated in the following example: ```php <?php $file = "note.txt"; // String of data to be written $data = "The quick brown fox jumps over the lazy dog."; // Open the file for writing $handle = fopen($file, "w") or die("ERROR: Cannot open the file."); // Write data to the file fwrite($handle, $data) or die ("ERROR: Cannot write the file."); // Closing the file handle fclose($handle); echo "Data written to the file successfully."; ?> ``` In the above example, if the "note.txt" file doesn't exist PHP will automatically create it and write the data. But, if the "note.txt" file already exist, PHP will erase the contents of this file, if it has any, before writing the new data, however if you just want to append the file and preserve existing contents just use the mode a instead of `w` in the above example. An alternative way is using the `file_put_contents()` function. It is counterpart of `file_get_contents()` function and provides an easy method of writing the data to a file without needing to open it. This function accepts the name and path to a file together with the data to be written to the file. Here's an example: ```php <?php $file = "note.txt"; // String of data to be written $data = "The quick brown fox jumps over the lazy dog."; // Write data to the file file_put_contents($file, $data) or die("ERROR: Cannot write the file."); echo "Data written to the file successfully."; ?> ``` If the file specified in the `file_put_contents()` function already exists, PHP will overwrite it by default. If you would like to preserve the file's contents you can pass the special `FILE_APPEND` flag as a third parameter to the `file_put_contents()` function. It will simply append the new data to the file instead of overwitting it. Here's an example: ```php <?php $file = "note.txt"; // String of data to be written $data = "The quick brown fox jumps over the lazy dog."; // Write data to the file file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the file."); echo "Data written to the file successfully."; ?> ``` ## Renaming Files with PHP rename() Function You can rename a file or directory using the PHP's `rename()` function, like this: ```php <?php $file = "file.txt"; // Check the existence of file if(file_exists($file)){ // Attempt to rename the file if(rename($file, "newfile.txt")){ echo "File renamed successfully."; } else{ echo "ERROR: File cannot be renamed."; } } else{ echo "ERROR: File does not exist."; } ?> ``` ## Removing Files with PHP unlink() Function You can delete files or directories using the PHP's `unlink()` function, like this: ```php <?php $file = "note.txt"; // Check the existence of file if(file_exists($file)){ // Attempt to delete the file if(unlink($file)){ echo "File removed successfully."; } else{ echo "ERROR: File cannot be removed."; } } else{ echo "ERROR: File does not exist."; } ?> ``` In the next chapter we will learn more about [parsing directories or folders](http://www.bixiaguangnian.com/manual/php7/3984.html "parsing directories or folders") in PHP. ## PHP Filesystem Functions The following table provides the overview of some other useful PHP filesystem functions that can be used for reading and writing the files dynamically. | Function | Description | |-----------------|------------------------------------------------------| | fgetc() | Reads a single character at a time. | | fgets() | Reads a single line at a time. | | fgetcsv() | Reads a line of comma-separated values. | | filetype() | Returns the type of the file. | | feof() | Checks whether the end of the file has been reached. | | is_file() | Checks whether the file is a regular file. | | is_dir() | Checks whether the file is a directory. | | is_executable() | Checks whether the file is executable. | | realpath() | Returns canonicalized absolute pathname. | | rmdir() | Removes an empty directory. | Please check out the PHP filesystem reference for other useful PHP filesystem functions.
上一篇:
PHP 包含文件
下一篇:
PHP 解析目录