How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Create a Folder If It Does Not Exist in PHP
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Create a Folder If It Does Not Exist in PHP
Web Development

How to Create a Folder If It Does Not Exist in PHP

how7o
By how7o
Last updated: May 22, 2026
5 Min Read
Create a folder in PHP if it does not already exist
SHARE

To create a folder if it does not already exist in PHP, check with is_dir() and create with mkdir($path, 0755, true). The third argument creates parent directories along the path — handy for date-based folders like uploads/2026/05/17 where multiple levels may be missing.

Contents
  • The one-liner
  • mkdir()‘s three arguments
  • is_dir() vs file_exists()
  • Race-safe variant for concurrent requests
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 on PHP 8.3. Originally published 2023-01-03, rewritten and updated 2026-05-17.

The one-liner

$upload_dir = 'uploads/' . date('Y/m/d');

if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

On the first request of the day, uploads/2026/05/17 is created (along with any missing parent like 2026 or 2026/05). On every subsequent request, is_dir() short-circuits and mkdir() isn’t called.

PHP mkdir if not exists — is_dir check, recursive flag, race-safe variant

mkdir()‘s three arguments

  • $pathname — relative or absolute path. Relative paths resolve from the current working directory, which is usually the script’s own location but can change if your code calls chdir(). Use absolute paths when in doubt.
  • $mode — Unix permissions in octal. 0755 (owner write, others read+execute) is a sane default. 0777 is world-write and almost never necessary. Ignored on Windows.
  • $recursive — when true, missing parent directories are created too. Defaults to false, which means a deep path with any missing parent fails.

is_dir() vs file_exists()

The source recipe used file_exists(), which works in the common case but has a subtle edge: if a regular file at uploads/2026 already exists (created in error somewhere), file_exists() returns true and you skip the directory creation — then any attempt to write a file inside uploads/2026/05/17/ fails because uploads/2026 isn’t a directory. is_dir() is more precise:

// Better
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

Race-safe variant for concurrent requests

Two requests can both pass the is_dir() check before either calls mkdir(); the second mkdir() then raises a warning (“File exists”). Under low traffic this is harmless, but for an API or upload handler that runs concurrently, the resilient pattern is:

if (!is_dir($upload_dir) && !@mkdir($upload_dir, 0755, true) && !is_dir($upload_dir)) {
    throw new RuntimeException("Failed to create directory: $upload_dir");
}

The second is_dir() after a suppressed mkdir() covers the race: if another request just created the folder, we’re fine; if mkdir() failed for a real reason (permissions, missing parent we can’t create), we throw.

Frequently asked questions

Should I use file_exists() or is_dir() to check?

is_dir() is more specific — it returns true only if the path exists and is a directory. file_exists() returns true for files, directories, and symlinks. If a file with the same name as your target folder already exists, file_exists() will report true and you’ll skip the mkdir, then your file write into the “directory” fails. Prefer is_dir().

Why 0755 instead of 0777?

0777 grants write permission to everyone on the server — including any other site or user on a shared host. 0755 gives owner write, group/other read-and-execute, which is enough for the web server to read files and for upload scripts (running as the same user) to write. Use 0777 only when you genuinely need world-write, which is rare.

What does the third argument true in mkdir() do?

It’s the $recursive flag — it tells mkdir() to create any missing parent directories along the path. Without it, mkdir('uploads/2026/05/17') fails if uploads/2026 doesn’t already exist. With true, every intermediate folder is created in one call, like mkdir -p on the command line.

Is the if (!is_dir()) check race-safe under heavy traffic?

Not strictly. Between the is_dir() check and the mkdir() call, another request can create the directory — then your mkdir() raises a warning. To handle this cleanly, suppress the warning and check the result: if (!is_dir($d) && !@mkdir($d, 0755, true) && !is_dir($d)) throw new Exception('mkdir failed');. The second is_dir() covers the race where another request just created it.

Related guides

  • How to Display PHP Errors
  • How to Add a Number of Days to a Date in PHP

References

PHP mkdir(): php.net/manual/en/function.mkdir.php. PHP is_dir(): php.net/manual/en/function.is-dir.php.

TAGGED:configurationfilesystemphp

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Convert an image to a base64 data URL in JavaScript How to Convert an Image to a Base64 String in JavaScript
Next Article Laravel login and registration system with scaffolding packages How to Create a Login and Registration System in Laravel
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Get the last item from a PHP array
Web Development

How to Get the Last Item from an Array in PHP

5 Min Read
WordPress custom avatar without a plugin — media uploader writes user meta, get_avatar filter renders the image
Web Development

How to Change a User Profile Picture in WordPress Without a Plugin

10 Min Read
Install Laravel on Ubuntu — terminal with composer create-project command and Laravel red-pillar icon
Web Development

How to Install Laravel on Ubuntu: Step-by-Step Guide

9 Min Read
Laravel run without .env file — env() fallback in config/app.php
Web Development

How to Run a Laravel Project Without a .env File

8 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?