从file.php创建/Var/www/html文件夹失败


Failing to create folder in /Var/www/html from file.php

我有一个AWS EC2服务器与phpMyAdmin来管理它。

一切工作正常,但我希望能够在/var/www/html目录中创建另一个文件夹来添加文件..

这是我的代码,但它只是不断返回错误给我!有什么想法?

// STEP 2.2 Create a folder in server to store posts'pictures
   $folder = "/var/www/html/bloggerFiles/Posts/" . $id;

if(!file_exists($folder)){
    if (!mkdir($folder, 0777, true)) {//0777
        die('Failed to create folders...');
    }
}

我通常会通过使用sudo mkdir在终端中创建该文件夹,但是当我添加sudo时,什么都不起作用!

任何帮助都是感激的!

确保您正在访问的文件夹设置为read and write文件夹权限,然后使用此函数:

function newFolder($path, $perms)
    $path = str_replace(' ', '-', $path);
    $oldumask = umask(0); 
    mkdir($path, $perms); // or even 01777 so you get the sticky bit set  (0777)
    umask($oldumask);
    return true;
}

这为我解决了这个问题。

你可以这样创建新文件夹:newFolder('PathToFolder/here', 0777);

EDIT:请查看:https://www.youtube.com/watch?v=7mx2XOFBp8M
编辑:也看看http://php.net/manual/en/function.mkdir.php#1207

EDIT:将函数存储在类中并安全地使用函数

class name_here
{
    public function newFolder($path, $perms, $deny_if_folder_exists){
        $path = 'PATH_TO_POSTS/'.$path; // This is for setting the root to PATH TO POSTS
        $path = str_replace('../', '', $path); // Deny the path to go out of var/www/html/PATH_TO_POSTS/$path
        if( $deny_if_folder_exists === true ){
            if(file_exists($path)){return false;}
            $old_umask = umask(0);
            mkdir($path, $perms);
            umask($old_umask);
        }elseif( $deny_if_folder_exists === false ){
            $old_umask = umask(0);
            mkdir($path, $perms);
            umask($old_umask);
        }else{
            return false; // Unknown
        }
    }
}
/* Call the function by doing this: */
$manage = new name_here;
$manage->newFolder('test', 777, true); // Test will appear in /var/www/html/PATH_TO_POSTS/$path, but if the folder exists it will return false and not create the folder.

EDIT:如果这个文件是从html中调用的,它将重新创建路径,所以我将它从/html/

中调用

EDIT:如何使用name_here类

/*
 How to call the function?
  $manage = new name_here; Creates a variable to an object (The class)
  $manage->newFolder('FolderName', 0777, true); // Will create a folder to the path,
  but this fill needs to be called from the html the root directory is set to the
  "PATH_TO_POSTS/" basicly means you cannot do this function from "html/somewhere/form.php",
  UNLESS the "PATH_TO_POSTS" is in the same directory as form.php
*/