For uploading, I want to check if the year folder and month sub-folder already exist. If they don't, I would like to create them and save my uploads there.
<?php
$newname = $_POST['changename'];
$temp = explode(".", $_FILES["uploadfile"]["name"]);
$extension = end($temp);
if(!(
$_FILES['uploadfile']['type']=='image/jpeg' ||
$_FILES['uploadfile']['type']=='image/png' ||
$_FILES['uploadfile']['type']=='image/gif' ||
$_FILES['uploadfile']['type']=='image/bmp'
)) // if file does not equal these types, kill it
{
echo $_FILES['uploadfile']['type'] . " is not an acceptable format.";
die();
}
if ($_FILES["uploadfile"]["size"] > 20000000)
{
echo "File too big. Max 20mb";
die();
}
if ($_FILES["uploadfile"]["error"] > 0)
{
echo "Return Code: " . $_FILES["uploadfile"]["error"] . "<br>";
}
else
{
$new_file_name = $newname.".".$extension;
$path = "uploads/".$new_file_name;
move_uploaded_file($_FILES["uploadfile"]["tmp_name"],$path);
echo json_encode(array(
"success" => true,
"imagepath" => $path,
"filetype" => $_FILES["uploadfile"]["type"],
"new_file_name" => $newname,
"fileName" => $_FILES["uploadfile"]["name"],
"fileTmp" => $_FILES["uploadfile"]["tmp_name"],
));
}
?>
Go with something like this:
$year = date("Y");
$month = date("m");
$filename = "../".$year;
$filename2 = "../".$year."/".$month;
if(file_exists($filename)){
if(file_exists($filename2)==false){
mkdir($filename2,0777);
}
}else{
mkdir($filename,0777);
}
You have to adjust this code depending on directory structure that you have. It shows you basic idea of checking whether the file or directory exists and if it's not, then it will be created you.
Adjusting your code to your need, it should be this (not tested):
$path = "uploads/";
$year_folder = $path . date("Y");
$month_folder = $year_folder . '/' . date("m");
!file_exists($year_folder) && mkdir($year_folder , 0777);
!file_exists($month_folder) && mkdir($month_folder, 0777);
$path = $month_folder . '/' . $new_file_name;
NOTE: Put it right above
move_uploaded_file($_FILES["uploadfile"]["tmp_name"],$path);