Jack Jack - 8 months ago 46
PHP Question

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

I have a AWS EC2 server with phpMyAdmin to manage it.

Everything is working correctly but I would like to be able to create another folder in the /var/www/html directory to add files..

This is my code but it just keeps returning the error to me! any ideas??

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

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


I would normally create that folder in the terminal by using sudo mkdir, but when I add sudo Nothing works!

Any help is appreciated!
Thanks in advance.


Make sure the folder(s) you are accessing are set to read and write folder permissions, then use this function:

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)
    return true;

This fixed it for me.

You can create new folder doing this: newFolder('PathToFolder/here', 0777);

EDIT: Please have a look at: https://www.youtube.com/watch?v=7mx2XOFBp8M
EDIT: Also have a look at http://php.net/manual/en/function.mkdir.php#1207

EDIT: Storing functions in classes and safely use the function

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

        }elseif( $deny_if_folder_exists === false ){
            $old_umask = umask(0);
            mkdir($path, $perms);
            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: If this file is called from html it will re create the path, so I will it has to be called from /html/