Take the 2-minute tour ×

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.

share|improve this question
web root directory !== filesystem root directory –  Mark Baker Oct 2 '13 at 10:25
add comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
add comment

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


if (file_exists('path/to/directory')) {
    echo "Folder Already Exists";
    mkdir('path/to/directory', 0777, true);
    echo "folder Created";
share|improve this answer
y r you down arrowing me ???????????? –  Faizan Khan Oct 2 '13 at 11:22
add comment

Your Answer


