CodeIgniter - Message: mkdir(): Permission denied

2019-02-27 11:01发布

问题:

I'd like some help please. I have this PHP script inside my Post_model constructor

$dir = FCPATH . 'uploads' . DIRECTORY_SEPARATOR . 'posts'; 
if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
} 

which shows me this error:

Severity: Warning

Message: mkdir(): Permission denied

The main idea is that the project has the ability to create users and these users can upload images, or create folders-albums which are stored in the uploads folder.

I've been struggling to fix this error the last days and can't find a solution. I have tried this code and on Windows and works great, but not on Linux (Ubuntu 14.04)

回答1:

Please try chmod 777 -R . in your directory



回答2:

Even i had same problem , i tried with umask, it worked. you can do like this,

$old = umask(0);
mkdir($dir, 0755, true);
umask($old);


回答3:

[How to Create Directory in PHP / CodeIgniter] (http://codedpoint.16mb.com/index.php/viewCode?topic=Create%20Directory%20-%20CodeIgnitor)



回答4:

I suggest you manually create 'uploads' folder and give it 777 permission (not recursive) and then in your php script do the following:

if(!is_dir('./uploads/posts')) //create the folder if if does not already exists { mkdir('./uploads/posts',0755,TRUE); }

by this, every time your script tries to create a new directory, it will have the permission to do so since you are creating the new directory inside uploads which has 777.



回答5:

the issue probably is the mask :)

if (!function_exists('mkdir_r')) {
    /**
     * create directory recursively
     * @param $dirName
     * @param int $rights
     * @param string $dir_separator
     * @return bool
     */
    function mkdir_r($dirName, $rights = 0744, $dir_separator = DIRECTORY_SEPARATOR) {
        $dirs = explode($dir_separator, $dirName);
        $dir = '';
        $created = false;
        foreach ($dirs as $part) {
            $dir .= $part . $dir_separator;
            if (!is_dir($dir) && strlen($dir) > 0) {
                $created = mkdir($dir, $rights);
            }
        }
        return $created;
    }
}

if (!function_exists('ensure_dir')) {
    /**
     * ensure directory exist if not create 
     * @param $dir_path
     * @param int $mode
     * @param bool $use_mask
     * @param int $mask
     * @return bool
     */
    function ensure_dir($dir_path, $mode = 0744, $use_mask = true, $mask = 0002) {
        // set mask 
        $old_mask = $use_mask && $mask != null
            ? umask($mask)
            : null;
        try {
            return is_dir($dir_path) || mkdir_r($dir_path, $mode);
        } finally {
            if ($use_mask && $old_mask != null) {
                // restore original
                umask($old_mask);
            }
        }
    }
}