PHP is a widely used server-side scripting language for developing dynamic web pages and applications. This article will show you how to create directories in PHP based on the current year, month, and day, which is useful for tasks such as file management and logging.
Sometimes, you may need to dynamically create directories by date, such as storing log files organized by the current date. Here's an example PHP code to achieve this:
$date = date('Y/m/d');
$dir = "logs/" . $date;
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
echo "Directory created: " . $dir;
} else {
echo "Directory already exists: " . $dir;
}
In this code, we use PHP's built-in date() function to get the current year, month, and day and format them as the directory path. Then, we check if the directory exists with file_exists() and, if not, use mkdir() to create it.
Besides creating directories by date, PHP provides many other directory functions that can help with file and directory management.
The mkdir() function is used to create directories. If the directory already exists, the third parameter can be used to create directories recursively.
mkdir('logs/2025/06/29', 0777, true);
You can use file_exists() to check if a directory exists.
if (file_exists('logs/2025/06/29')) {
echo 'Directory exists';
} else {
echo 'Directory does not exist';
}
If you need to delete an empty directory, you can use the rmdir() function.
rmdir('logs/2025/06/29');
You can use the scandir() function to retrieve the list of files and subdirectories within a directory.
$files = scandir('logs/2025/06/29');
print_r($files);
This article demonstrated how to create directories by year, month, and day using PHP, along with relevant code examples. By using PHP's built-in functions such as date(), mkdir(), and file_exists(), you can easily perform directory creation, checking, and deletion operations. These tips will help streamline file management in various scenarios.