为什么PHP认为此文件夹不存在? [英] Why does PHP think this folder doesn't exist?
问题描述
我在创建文件夹和写入文件夹时遇到麻烦.
I'm having trouble creating a folder and writing into it.
if(file_exists("helloFolder") || is_dir("helloFolder")){
echo "folder already exists";
} else {
echo "no folder, creating";
mkdir("helloFolder", 0755);
}
即使文件夹已经存在,它也会返回"no folder, creating"
.然后我得到这个错误:
This returns "no folder, creating"
even when the folder already exists. Then I get this error:
Warning: mkdir() [function.mkdir]: No such file or directory in script.php on line 18
警告:file_put_contents(/filename.txt)[function.file-put-contents]:无法打开流:58行的script.php中的权限被拒绝
Warning: file_put_contents(/filename.txt) [function.file-put-contents]: failed to open stream: Permission denied in script.php on line 58
非常奇怪的是,我调用了三个单独的脚本来执行此操作,尽管一个脚本始终有效,但另外两个始终会出现此错误.我正在同步调用脚本,所以我认为没有任何重叠之处.他们之间的其他一切都一样.全部具有权限644
,所有文件夹均具有权限755
.
What is very strange is that I call three separate scripts that do this, and while the one always works, the other two always give this error. I'm calling the scripts synchronously, so I don't think there's any overlapping going on. Everything else is the same between them. All have permissions 644
, all folders have permission 755
.
推荐答案
首先,在使用FileSystem时应遵循绝对补丁,而且还存在两个小缺陷:
First of all, you should adhere to the absolute patches when working with FileSystem, and also there are two minor flaws:
-
is_dir()
-检查文件是否存在及其目录.因此file_exists()
有点多余.
is_dir()
- Checks whether file exists and its a directory. Thereforefile_exists()
is kinda redundant.
如果在其他任何地方使用相同的字符串,最好将其值保存在变量中.
If you work with the same string anywhere else, it would be better to save its value in a variable.
最后,您的代码应如下所示,
And finally, your code should look like this,
$target = dirname(__FILE__) . '/hellodir';
if (is_dir($target)) {
echo "folder already exists";
} else {
echo "no folder, creating";
// The 3-rd bool param includes recursion
mkdir($target, 0777, true);
}
这将按预期工作.
这篇关于为什么PHP认为此文件夹不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!