gpt4 book ai didi

php - 脚本在魔术方法 __destruct() 中失去权限

转载 作者:可可西里 更新时间:2023-10-31 22:52:04 26 4
gpt4 key购买 nike

我试图在对象实例化时创建一个文件,并在对象销毁时创建另一个文件。

代码如下:

class Foo{
public function __construct(){
file_put_contents('a_construct.txt', 'c');
}
public function __destruct(){
file_put_contents('a_destruct.txt', 'd');
}
}

通常会创建a_construct.txt 文件。但是在创建 a_destruct.txt 文件时,它的行为很奇怪。

如果我运行以下代码,“a_destruct”文件不会被创建。

$foo = new Foo();

我得到这个错误:

Warning: file_put_contents(a_destruct.txt): failed to open stream: Permission denied


现在,如果我运行以下命令并检查文件夹,文件就在那里。

$foo = new Foo();
unset($foo);

我尝试过的:

  • 将名称从 construct 交换到 destruct 并返回,但它始终仅适用于 __construct 方法;
  • 在方法上添加输出以确认它们正在被调用 - 它们是(并且对于两个测试代码)。

第二个测试代码显示我确实有创建文件的权限。

但是第二个主题告诉我,当我让对象在脚本末尾被销毁时,我正在“失去”权限(因为我确定正在调用该方法)。


这是什么原因造成的以及如何解决?

最佳答案

修复它,您可以使用完整路径:

public function __destruct(){
file_put_contents(dirname(__FILE__) . '/a_destruct.txt', 'd');
}

这记录在 manual 中:

The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).


这意味着您正在尝试在不同的目录中创建文件 - 并且您没有权限访问该目录。

这就是当您运行 unset($foo) 时它起作用的原因 - 因为它尚未处于关闭阶段。


尽管我不建议在关闭阶段弄乱工作目录,但我想证明这是可能的:

public function __destruct(){
$tmp = getcwd(); // get current working dir
chdir(dirname(__FILE__)); // set it to be same as the file
file_put_contents('a_destruct.txt', 'd');
chdir($tmp); // set the working dir back to what it was before
}

关于php - 脚本在魔术方法 __destruct() 中失去权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com