rockstardev
rockstardev

Reputation: 13527

PHP Mkdir not executing recursively?

The following works in windows:

mkdir('../my/folder/somewhere/on/the/server', 0777, true);

I am talking about PHP mkdir.

It works perfectly, and creates the subfolders recursively. However, if I run the same command on a linux server, the folders aren't created.

Previously I solved this by breaking up the path and creating each folder one by one. But I don't want to do that because it should work with the "resurive" flag set to true. Why isn't it working?

Upvotes: 2

Views: 4101

Answers (3)

jamsandwich
jamsandwich

Reputation: 385

Make sure that your PHP user (eg www-data) has permission to write to the parent folders of any folder it is trying to create. PHP needs to be able to write to the lowest one that already exists.

For example, in the case of ../my/folder/somewhere/on/the/server, if ../my already exists and PHP is able to write to .. but not to my, mkdir will fail.

If your user is www-data, you could use sudo chown -R www-data:www-data ../my to give write permission for my and all its subfolders.

Upvotes: 1

Baba
Baba

Reputation: 95101

This are the thing have discovered

  • Make sure the root path exists
  • Make sure the root path is writable
  • Don't use .. always use real path ...

Example

$fixedRoot = __DIR__;
$recusivePath = 'my/folder/somewhere/on/the/server';

if (is_writable($fixedRoot) && is_dir($fixedRoot)) {
    mkdir($fixedRoot . DIRECTORY_SEPARATOR . $recusivePath, 0, true);
} else {
    trigger_error("can write to that path");
}

Upvotes: 1

arkascha
arkascha

Reputation: 42915

Sorry, but there must be some problem apart from the mkdir command itself.

This tiny example works as expected and recursively creates the directories for me when executed on Linux:

#!/usr/bin/php
<?php
mkdir ('testdir/testdir2/testdir3',0777,TRUE);
?>

Upvotes: 3

Related Questions