mkdir always sets folders to read-only?

后端 未结 3 1686
时光取名叫无心
时光取名叫无心 2021-01-25 23:42

i am trying to create folders from within php. Whenever i use the mkdir function with permission 0777 i get a read-only folder. I want this folder to be read & write. The p

相关标签:
3条回答
  • 2021-01-26 00:21

    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 new 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 mask 
                    umask($old_mask);
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-26 00:22

    You can have write permission too with mkdir..Here is the code

    <?php
     $dir = 'myDir';
     // create new directory with 744 permissions if it does not exist yet
     // owner will be the user/group the PHP script is run under
    
     if ( !file_exists($dir) ) {
    mkdir ($dir, 0744);
    }
    
     file_put_contents ($dir.'/test.txt', 'Hello File');
    

    Found the source from here

    0 讨论(0)
  • 2021-01-26 00:31

    In a shared environment, mkdir fails to set the permissions properly. A workaround is to set the chmod with chmod() after you've created the directory.

    0 讨论(0)
提交回复
热议问题