I am using this function in codeigniter to try to check and make directories and sub directories only if they do not exist. Only the k_uploads is made but an error occurs in making the sub directory in the main directory 'k_upoloads'. The structure should be as
k_uploads (main directory)
-2012 (subdirectory in main directory - made per year in k_uploads)
-Jan(subdirectory in 2012 - made every month in 2012)
-subdirx (subdirectory in Jan - holds the excel files for that month)
xxyyy.xlsx (month files in subdirx)
Each year and month directories and sub directories should be created. I cant figure where the problem is, it works with plain php but not in codeigniter.
public function makeDir(){
$labref = $this->uri->segment(3);
$dirName='k_uploads';
echo $store_dir= date('Y').'/'.date('M').'/'.$subdirx;
if(!is_dir($dirName))
$k= mkdir($dirName, 0777);
if($k){
echo $dirName. 'dir has been created';
}else{
echo 'An error occured';
}
if(is_dir($dirName))
$w= mkdir($store_dir,0777);
if($w){
echo $sore_dir. 'subdirs have been created';
}else{
echo 'An error occured';
}
}
mkdir
has a recursive flag which can be set. This will create the full path. See PHP: mkdir
so you should use mkdir($store_dir,0777, true)
The function could look something like the following:
public function makeDir(){
$subdirx = $this->uri->segment(3);
$store_dir= APPPATH . 'k_uploads/' . date('Y').'/'.date('M').'/'.$subdirx;
if(!is_dir($store_dir)) {
return mkdir($dirName, 0777, true);
} else {
return true;
}
}
In order to do this, you will need to create each sub-directory in a sequence, as PHP will not do this for you. You might want to check if the directory already exists using is_dir()
while doing so.
Here's an example:
function createDir($dirToMake) {
$root = "/home/sites/test/www/";
$dArray = explode("/",$dirToMake);
if (file_exists($root) && is_dir($root)) {
// just a quick check
if (substr($root,0,-1) !== "/") $root .= "/";
foreach ($dArray as $v) {
if (strlen($v) == 0) continue;
$root = $root.$v."/";
if (file_exists($root) && is_dir($root)) continue;
mkdir($root);
}
}
else throw new Exception("Root directory does not exist");
}
This function also allows for the usual mistakes (// being one of them), and will loop through, creating the sub-directory architecture needed if it doesn't exist already.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.