php 创建,打开,读取,写入,追加,关闭和删除

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 创建,打开,读取,写入,追加,关闭和删除相关的知识,希望对你有一定的参考价值。

//Create a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file

//Open a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //open file for writing ('w','r','a')...

//Read a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));

//Write to a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
$data = 'This is the data';
fwrite($handle, $data);

//Append to a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file:  '.$my_file);
$data = 'New data line 1';
fwrite($handle, $data);
$new_data = "\n".'New data line 2';
fwrite($handle, $new_data);

//Close a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
//write some data here
fclose($handle);

//Delete a File
$my_file = 'file.txt';
unlink($my_file);

//Create a folder if it is not exist
if (!file_exists('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}

以上是关于php 创建,打开,读取,写入,追加,关闭和删除的主要内容,如果未能解决你的问题,请参考以下文章

Python知识点梳理:文件处理

PHP

python 文件操作

fs模块主要功能小解

文件操作和函数

PHP:php知识小解