Home php教程 php手册 PHP编程中八种常见的文件操作方式

PHP编程中八种常见的文件操作方式

Jun 13, 2016 pm 12:36 PM
php superior and deal with common operate document Way yes server local of Table of contents programming

文件和目录的操作
PHP处理本地服务器上的文件和目录是非常方便的,但有时候会出现权限和路径相关的问题
1.打开文件
resource fopen ( string filename, string mode [, bool use_include_path [, resource zcontext]] )
$handle = fopen(filename,mode)//打开文件,返回代表此文件的资源的句柄
文件名称可以使用相对路径或者绝对路径也可以使用网络协议模式,打开模式具有r\r+\w\w+\a\a+\x\x+\b
在操作二进制文件时如果没有指定 'b' 标记,可能会碰到一些奇怪的问题,包括坏掉的图片文件以及关于 \r\n 字符的奇怪问题。
为移植性考虑,强烈建议在用 fopen() 打开文件时总是使用 'b' 标记。
以下是几种打开文件的方式
$fp = @fopen('log.txt',"rb");
$fp = @fopen('../log.txt',"rb");
$fp = @fopen("http://www.runer.com.cn/default.htm","rb");//还可以使用ftp和ghoper等协议,必须启用php.ini文件中的allow_url_fopen选项
////////////////////////////代码部分////////////////////////////////////////
$filename1 = "userinfo.txt";//目录下或include_path中存在这个文件
$filename2 = "test.txt";//目录下或include_path并不存在这个文件
$resource1 = fopen($filename1,"rb");
@$resource2 = fopen($filename2,"rb");//因为目录中不存在这个文件,并且并未使用或include_path寻找包含文件所在路径则此操作会报错,使用错误抑制符@可以迫使浏览器不输出错误信息
if($resource1)
echo "打开文件{$filename1}成功";
if(!@fopen($filename2,"r"))
echo "打开文件{$filename2}不成功";
//////////////////////////////////////////////////////////////////////////
---------------------输出结果----------------------------------------
打开文件userinfo.txt成功

---------------------------------------------------------------------
2.使用完毕文件后,要显式的告诉PHP已经使用完文件,让操作系统确保将文件的所有内容正确地从缓冲区刷新到硬盘
使用fclose()关闭文件,
bool fclose ( resource handle )//关闭一个已打开的文件指针
3.读取文件,fopen函数的mode参数允许读取,PHP提供了几个函数从文件读取数据
string fgets ( int handle [, int length] )从文件指针中读取一行,在二进制文件上尝试fgets会产生不可预测的结果
如果不指定长度,默认读取1K数据,碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止
string fgetss ( resource handle [, int length [, string allowable_tags]] )从文件指针中读取一行并过滤掉 HTML 标记
fgetc()读取单个字符
fread()读取任意二进制数据
////////////////////////////代码部分////////////////////////////////////////
$handle = fopen ("test.jpg", "rb");
$c;
while (!feof($handle)) {
$contents .= @fread($handle, 8192);//循环读取并将其合并为一个大块文件
}
fclose($handle);
//////////////////////////////////////////////////////////////////////////
---------------------输出结果----------------------------------------

---------------------------------------------------------------------
4.判断文件读取的状态
每个文件句柄都有一个文件指针,或者一个指出下一个操作将在文件中哪里发生的游标,根据fopen函数的mode参数
文件指针最初位于文件的开头(0),或者文件的末尾
feof()可以判断文件是否已经到末尾(到末尾后函数返回TRUE)
filesize()函数返回文件的大小 5.写入文件
fwrite()函数执行文件写入
////////////////////////////代码部分////////////////////////////////////////
$filename = 'test.txt';
$somec;
// 首先我们要确定文件存在并且可写。
if (is_writable($filename)) {
// 在这个例子里,我们将使用添加模式打开$filename,
// 因此,文件指针将会在文件的开头,
// 那就是当我们使用fwrite()的时候,$somecontent将要写入的地方。
if (!$handle = fopen($filename, 'a')) {
echo "不能打开文件 $filename";
exit;
}
// 将$somecontent写入到我们打开的文件中。
if (fwrite($handle, $somecontent) === FALSE) {
echo "不能写入到文件 $filename";
exit;
}
echo "成功地将 $somecontent 写入到文件$filename";
fclose($handle);
} else {
}
echo "文件 $filename 不可写";
//////////////////////////////////////////////////////////////////////////
---------------------输出结果----------------------------------------
成功地将 添加这些文字到文件 写入到文件test.txt
---------------------------------------------------------------------
对于二进制数据,必须指定第三个参数,它包含写入到磁盘的数据字节数
$result = @fwrite($fp,$binary_data,mb_strlen($binary_data,'8bit'));
6.文件权限和其他信息
is_readable()//判断文件是否可读
is_writeable()//判断文件是否可写
is_writable()//判断文件是否可写
fileperms()//判断文件的权限(UNIX风格的文件权限测试函数)
file_exists()//是否存在这个文件
fileowner()//判断文件所属用户
filegroup()//判断文件所属组
7.删除和重命名文件
unlink()//删除文件
rename()//重命名文件
8.访问目录
目录访问建议使用前向斜线"/",兼容windows和unix系统
basename()//返回不包括路径信息的文件名
dirname()//返回文件名的目录部分
realpath()//接受相对路径,返回文件的绝对路径
pathinfo()//提取给定路径的目录名,基本文件名和扩展名
opendir()//打开目录,返回资源句柄
readdir()//读取目录项
rewinddir()//将读取指针返回开头
closedir()//关闭读取句柄
chdir()//改变当前脚本执行期间的当前工作目录
mkdir()//创建目录
rmdir()删除目录
////////////////////////////代码部分////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
---------------------输出结果----------------------------------------

filename: web : filetype: dir

filename: study : filetype: dir

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 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
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles