php文件系统允许我们创建文件,逐行读取文件,逐个字符读取文件,写入文件,附加文件,删除文件和关闭文件。
php fopen()
函数用于打开文件。
语法
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
示例
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
// 或者
$handle2 = fopen("c:/folder/file.txt", "r");
?>
php fclose()
函数用于关闭打开的文件指针。
语法
boolean fclose ( resource $handle )
示例代码
<?php
fclose($handle);
?>
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,this is php read file - fread()...
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()
函数用于删除文件。
语法
bool unlink ( string $filename [, resource $context ] )
示例
<?php
unlink('data.txt');
echo "file deleted successfully";
?>