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
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026

You Might Also Like

WordPress too many redirects HTTPS — Cloudflare flexible SSL loop and the wp-config fix
Web Development

Fix ERR_TOO_MANY_REDIRECTS in WordPress After Switching to HTTPS

7 Min Read
Laravel updateOrCreate method shown in an Eloquent code snippet with insert and update branches
Web Development

Laravel updateOrCreate: Insert or Update Records in Eloquent

8 Min Read
yum/dnf -y flag explained
Server Management

What Does the -y Flag Do in yum / dnf / apt-get?

5 Min Read
Keep only the digits in a JavaScript string with regex
Web Development

How to Keep Only Numbers in a String with JavaScript

4 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?