Why does PHP think this folder doesn't exist?

你。 提交于 2019-12-02 20:04:48

问题


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);
}

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

Warning: file_put_contents(/filename.txt) [function.file-put-contents]: failed to open stream: Permission denied in script.php on line 58

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.


回答1:


First of all, you should adhere to the absolute patches when working with FileSystem, and also there are two minor flaws:

  • is_dir() - Checks whether file exists and its a directory. Therefore file_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);
}

This will work as expected.




回答2:


Try this code for creating folder if folder not exists there:

<?php 

if (file_exists('path/to/directory')) {
    echo "Folder Already Exists";
}
else{
    mkdir('path/to/directory', 0777, true);
    echo "folder Created";
}
?>


来源:https://stackoverflow.com/questions/19134550/why-does-php-think-this-folder-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!