我在 Windows/Wamp 环境中创建了一个具有缓存脚本的应用程序。该脚本的缓存功能同时只允许运行一次。
为了实现这一点,我使用了一个“锁定文件”并检查它是否存在。
在 Windows 上,此脚本继续正常工作。但是现在移到Ubuntu环境是不行的。
<?php
date_default_timezone_set('Europe/Amsterdam');
ini_set('max_execution_time', 300);
ignore_user_abort(true);
$path = 'locked.txt';
if ($lock = fopen($path,'x+')) {
fwrite($lock,time());
fclose($lock);
sleep(10);
unlink($path);
}
?>
错误:fopen(locked.txt):无法打开流:权限被拒绝
最佳答案
来自 PHP 文档(稍作解释):
x+ Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
根据您的描述,您正在尝试使用“x+”标志将文件用作锁定文件,以确保您没有锁定已经锁定的文件。
问题是从 Windows 迁移到 *NIX 系统(如 Ubuntu),您需要熟悉权限系统的差异。
短篇小说是:
每个文件和文件夹都“属于”一个用户。
想要在目录中创建文件的用户至少需要对该目录具有执行和写入权限。
考虑到这一点,您需要确保当前用户对脚本具有目录的写入和执行权限,并且要实际执行脚本,他们还需要对该目录具有读取权限(在除了脚本的读取权限)。确保该目录对运行脚本的用户具有读写执行权限(标志号 7)。
如果您通过 Web 界面运行脚本,则该用户将为 www-data
。
一般来说,chmod 777/directory/with/script
应该可以工作,并为所有用户授予目录的读写执行权限。
关于PHP fopen 'x+' 在 ubuntu 上不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36648232/