php - 打开同一个 .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”
解决方案
使用 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'";
}
推荐阅读
- angular - 来自枚举值字符串的枚举数组
- docker - 如何将端口映射动态传递给 docker-compose up 命令?
- c# - LockBits/UnlockBits 在 C# 中有什么作用?
- parsing - 我可以向 System.Linq.Dynamic.Core 添加更多功能吗?
- powerbi - 带有切片器的 DAX DateDiff
- syntax - 为什么开发人员倾向于编写此代码,而不是其他方式?
- python - 在 Python 中模拟共享库 (.so) 函数
- vue.js - 如何在我的 Nuxt 项目中全局使用 sass?
- ssis - 如何通过脚本任务在 ssis 的特定文件夹中发送文件
- javascript - tobias ahlin 的移动字母用于多个标题