0

I'm having a small issue here with my php where I'm trying to create a directory but when the code is ran I get the error message

Warning: mkdir() [function.mkdir]: No such file or directory

Can anyone give me some guidance as to where I'm going wrong here?

<?
    function generateRandomString($length = 10) {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    $Key = generateRandomString();

    if(is_dir("Server1/".$Key) === true){
        header("Refresh:0");
    }
    else
    {
        mkdir("Server1/".$Key);
        echo $Key;
    }

?>
4
  • 2
    check if Server1 exists Commented Apr 29, 2017 at 11:24
  • Server1 100% exists as the document I'm writing the php in is saved in this directory Commented Apr 29, 2017 at 11:25
  • Then you should be leaving out the Server1 part, or be using an absolute path. Right now you are referring to Server1/Server1/$key Commented Apr 29, 2017 at 11:26
  • Ahhh that makes so much sense, Thanks John V "lifesaver" Commented Apr 29, 2017 at 11:29

3 Answers 3

1

As per the documentation:

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

You need to set recursive to true:

recursive

Allows the creation of nested directories specified in the pathname.

Alternatively, if you expect the sub path to exist, you may want to check your path is correct.

Sign up to request clarification or add additional context in comments.

Comments

0
if(is_dir("Server1/".$Key) === true){
    header("Refresh:0");
}
else
{
    mkdir("Server1/".$Key);
    echo $Key;
}

The call to is_dir() fails when the directory "Server1/".$Key does not exist but it also fails when the directory Server1 does not exist.

On the other hand, by default, mkdir() does not create the intermediate directories when they do not exist. If the directory Server1 does not exist then is_dir() returns FALSE and mkdir() fails with the error message "No such file or directory".

It makes sense because in order to create the directory "Server1/".$Key it must first go to the "Server1/" directory and create the sub-directory $Key inside it.

You can make it work by passing TRUE as the third argument of mkdir():

mkdir("Server1/".$Key, 0777, TRUE);

Comments

0

If your php script is in the "Server1" directory you dont want to use "Server1" in mkdir...

Just use mkdir($Key);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.