首页 > 解决方案 > 打开同一个 .txt 文件以在两个不同的 php 中写入

问题描述

在我的第一个 php 文件中,我打开 users.txt 来读取它,然后写入它。这是它的代码:阅读:

if(file_exists("users.txt")){
    $handle = fopen("users.txt", "r");
    if ($handle) {
        ...
    } else {
        $ERROR = "Can't open the 'users.txt' file";
    }
    if ($userExist === true) {
        ...
    }
    else {
        ...
    }
} else {
        ...
}

写:

$file = fopen("users.txt", "a") or die("Unable to open the file");
$data = PHP_EOL. $UserId . " " . $Fname . " " . $Lname . " " . $pass;
fwrite($file, $data);
fclose($file);

在我的第二个 php 文件中,我尝试打开同一个文件,但显然是在执行此代码时:

$file = fopen("users.txt", "a") or die("Unable to open the file");
if (file_exists($file)) {
    $data = " " . $Phone . " " . $recoveryEmail . " " . $month . " " . $day . " " . $year . " " . $gender;
    fwrite($file, $data);
    fclose($file);
}
else{
    echo "Can't open the file 'users.txt'";
}

当我运行它时,我的第一个 php 文件一切正常,但第二个它打印消息:

无法打开文件“users.txt”

标签: phpfile

解决方案


使用 fopen 函数后,$file 是句柄,而不是文件名。

因此请作如下修改:


$file = fopen("users.txt", "a") or die("Unable to open the file");
if (file_exists("users.txt")) {
    $data = " " . $Phone . " " . $recoveryEmail . " " . $month . " " . $day . " " . $year . " " . $gender;
    fwrite($file, $data);
    fclose($file);
}
else{
    echo "Can't open the file 'users.txt'";
}

推荐阅读