PHP教程
PHP Mysql
PHP面向对象
PHP常用

PHP 文件处理

PHP 文件处理

PHP 文件系统允许我们创建文件、逐行读取文件、逐字符读取文件、写入文件、追加文件、删除文件和关闭文件.

PHP 打开文件-fopen()

PHP fopen() 函数用于打开文件。
语法
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
示例
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>

PHP 关闭文件-fclose()

PHP fclose() 函数用于关闭打开的文件指针。
语法
ool fclose ( resource $handle )
示例
<?php
fclose($handle);
?>

PHP 读取文件-fread()

PHP fread() 函数用于读取文件的内容。它接受两个参数: 资源和文件大小。
语法
string fread ( resource $handle , int $length )
示例
<?php  
$filename = "c:\\myfile.txt";  
$handle = fopen($filename, "r");//open file in read mode  
$contents = fread($handle, filesize($filename));//read file  
echo $contents;//printing data of file
fclose($handle);//close file  
?>  
输出
hello php file

PHP 写入文件-fwrite()

PHP fwrite() 函数用于将字符串的内容写入文件。
语法
int fwrite ( resource $handle , string $string [, int $length ] )
示例
<?php
$fp = fopen('data.txt', 'w');//open file in write mode
fwrite($fp, 'hello ');
fwrite($fp, 'php file');
fclose($fp);
echo "File written successfully";
?>
输出
File written successfully

PHP 删除文件-unlink()

PHP unlink() 函数用于删除文件。
语法
bool unlink ( string $filename [, resource $context ] )
示例
<?php  
unlink('data.txt');
 
echo "File deleted successfully";
?>
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4