【问题标题】:Open the same .txt file to write in it in two different php [duplicate]打开相同的 .txt 文件以在两个不同的 php 中写入 [重复]
【发布时间】:2020-12-04 03:16:27
【问题描述】:

在我的第一个 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'

【问题讨论】:

    标签: php file


    【解决方案1】:

    使用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'";
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-20
      • 2022-01-20
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多