PHP fopen 'x+' 不适用于 ubuntu
PHP fopen 'x+' doesn't work on ubuntu
我在 Windows/Wamp 环境中创建了一个具有缓存脚本的应用程序。此脚本的缓存功能只允许同时运行一次
为了实现这一点,我使用了 'locking file' 检查它是否存在。
在 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): failed to open stream: Permission denied
来自 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),您需要熟悉权限系统的差异。
短篇小说是:
每个文件和文件夹"belongs"一个用户。
想要在目录中创建文件的用户至少需要对该目录具有执行和写入权限。
考虑到这一点,您需要确保当前用户对 目录 具有脚本的写入和执行权限,并且要实际执行脚本,他们还需要读取权限在目录上(除了脚本的读取权限)。确保该目录对用户 运行 脚本具有读写执行权限(标志号 7)。
如果您是 运行 通过 Web 界面编写的脚本,则此用户将是 www-data
。
一般来说 chmod 777 /directory/with/script
应该可以工作并为所有用户授予目录的读写执行权限。
我在 Windows/Wamp 环境中创建了一个具有缓存脚本的应用程序。此脚本的缓存功能只允许同时运行一次
为了实现这一点,我使用了 'locking file' 检查它是否存在。
在 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): failed to open stream: Permission denied
来自 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),您需要熟悉权限系统的差异。
短篇小说是:
每个文件和文件夹"belongs"一个用户。
想要在目录中创建文件的用户至少需要对该目录具有执行和写入权限。
考虑到这一点,您需要确保当前用户对 目录 具有脚本的写入和执行权限,并且要实际执行脚本,他们还需要读取权限在目录上(除了脚本的读取权限)。确保该目录对用户 运行 脚本具有读写执行权限(标志号 7)。
如果您是 运行 通过 Web 界面编写的脚本,则此用户将是 www-data
。
一般来说 chmod 777 /directory/with/script
应该可以工作并为所有用户授予目录的读写执行权限。