PHP文件基础知识
1.创建和写入文件
您可以使用PHP中的fopen()函数来创建并打开文件句柄(文件目录)。文件指针代表了文件的状态、位置等多种信息,通过它可以对文件进行读、写等操作。
$file = fopen("example.txt", "w") or die("Unable to open file!"); //创建并打开文件
$txt = "John Doe\n"; //要写入文件的内容
fwrite($file, $txt); //写入文件
$txt = "Jane Doe\n"; //要写入文件的内容
fwrite($file, $txt); //写入文件
fclose($file); //关闭文件句柄
上面的代码中,我们使用fopen()函数创建并打开一个example.txt文件,模式为“w”(写入模式,如果文件已存在,则会被清除)。接下来,我们使用 fwrite() 函数将内容写入文件,最后使用 fclose() 函数关闭文件句柄。执行代码后,example.txt文件中会出现两行“John Doe”和“Jane Doe”。
除了“w”模式外,fopen()函数还支持其他模式,如“r”(只读模式)、“a”(添加模式)、“x”(独占模式)等.
2。文件读取
在PHP中,可以使用函数fgets()逐行读取文件内容。
$file = fopen("example.txt", "r") or die("Unable to open file!"); //打开文件
while(!feof($file)) { //循环读取文件内容
echo fgets($file) . "
";
}
fclose($file); //关闭文件句柄
上面的代码中,我们使用fgets()函数逐行读取example.txt文件的内容,并在每行后面添加
标签,最后关闭文件句柄。
除了 fgets() 函数之外,PHP 还提供了以下用于读取文件内容的函数:
- fgetc():逐字符读取文件内容
- fread():读取指定长度的文件内容
- file():将整个文件读入数组
3。文件处理功能
PHP提供了很多文件处理函数,用于判断文件是否存在、复制文件、删除文件等。
1。判断文件是否存在
您可以使用 PHP 中的 file_exists() 函数来确定文件是否存在。
$filename = "example.txt";
if(file_exists($filename)) {
echo "The file $filename exists.";
} else {
echo "The file $filename does not exist.";
}
2。复制文件
您可以使用 PHP 中的 copy() 函数来复制文件。
$source = "example.txt";
$destination = "backup/example.txt";
if (!copy($source, $destination)) {
echo "Failed to copy $source to $destination.";
} else {
echo "File copied from $source to $destination.";
}
3。删除文件
您可以使用 PHP 中的 unlink() 函数来删除文件。
$filename = "example.txt";
if (!unlink($filename)) {
echo "Failed to delete $filename.";
} else {
echo "File deleted: $filename.";
}
除了上述函数之外,PHP还提供了很多其他的文件操作函数,比如rename()函数(重命名文件)、filetime()函数(返回文件的最后修改时间)等。
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
上一篇:PHP 中 in_array 函数的用法和示例 下一篇:PHP 标头用户指南
code前端网