您的位置:

PHP File基础知识

一、文件的创建和写入

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"(独占模式)等。

二、文件读取

PHP中可以使用fgets()函数逐行读取文件内容。

    $file = fopen("example.txt", "r") or die("Unable to open file!");  //打开文件

    while(!feof($file)) {   //循环读取文件内容
        echo fgets($file) . "
"; } fclose($file); //关闭文件句柄

在上述代码中,我们使用了fgets()函数逐行读取example.txt文件的内容,并且在每行后面加上了<br>标签,最后关闭了文件句柄。

除了fgets()函数,PHP还提供了以下函数用于读取文件内容:

  • fgetc():逐字符读取文件内容
  • fread():读取指定长度的文件内容
  • file():将整个文件读入数组中

三、文件操作函数

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()函数(重命名文件)、filemtime()函数(返回文件最后修改时间)等。