Create folder if it doesn't exist: the right way in PHP
Hello everyone! I'm new to PHP and trying to make a simple CMS on WordPress. I need to create a directory by date when uploading images to the server, for example /uploads/2024/03/. But I keep getting the error "failed to open stream: No such file or directory" if the folders don't exist yet.
Here's my current code:
$path = '/var/www/html/uploads/' . date('Y/m');
$file = $path . '/image.jpg';
// Trying to save the file
file_put_contents($file, $data);
I already tried using mkdir($path) before writing, but the folder still isn't created. I googled it — people say I need to check for existence. I added a check:
if (!file_exists($path)) {
mkdir($path);
}
But now I get the error "mkdir():
No answers yet.
Log in to leave an answer