Open In App

How to Create a Folder if It Doesn’t Exist in PHP ?

We can easily create a folder in PHP, but before that, you have to check if the folder or directory already exists or not. So In this article, you will learn both to Check and Create a folder or directory in PHP. 

Methods:



  1. file_exists(): It is an inbuilt function that is used to check whether a file or directory exists or not.
  2. is_dir(): It is also used to check whether a file or directory exists or not.
  3. mkdir() :  This function creates a directory.

Method 1: Using file_exists() function: The file_exists() function is used to check whether a file or directory exists or not.

Syntax:



file_exists( $path )

Parameters: The file_exists() function in PHP accepts only one parameter $path. It specifies the path of the file or directory you want to check.

Return Value: It returns True on success and false on failure. 

Example:




<?PHP
      
// Checking whether file exists or not
$file_path = '/user01/work/gfg.txt';
  
if (file_exists($file_path)) {
    echo "The Given file already exists in GEEKSFORGEEKS directory";
}
else {
    echo "The file path doesn't exists in GeeksforGeeks directory";
}
  
?>

Output
The file path doesn't exists in GeeksforGeeks directory

Method 2: Using is_dir() function: The is_dir() function is used to check whether the specified file is a directory or not.

Syntax:

is_dir( $file )

Parameters: The is_dir() function in PHP accepts only one parameter. It specifies the path of the file or directory that you want to check.

Return Value: It returns True if the file is a directory otherwise returns false.

Example:




<?php
    
$gfg_directory = "https://www.geeksforgeeks.org";
  
    
// Checking whether a file is directory or not
if (is_dir($gfg_directory))
    echo ("Given $gfg_directory exists in GeeksforGeeks Portal");
else
    echo ("Given $gfg_directory doesn't exists in GeeksforGeeks Portal");
  
?>

Output
Given https://www.geeksforgeeks.org doesn't exists in GeeksforGeeks Portal

Method 3: Using mkdir() function: The mkdir() creates a new directory with the specified pathname.

Syntax:

mkdir(path, mode, recursive, context)

Parameters:

1

Example: This example checks the file exists or not and if file doesn’t exist then create a new file using mkdir() function.




<?php
  
$file_path = '/user01/work/gfg.txt';
  
// Checking whether file exists or not
if (!file_exists($file_path)) {
  
    // Create a new file or direcotry
    mkdir($file_path, 0777, true);
}
else {
    echo "The Given file path already exists";
}
?>

Output:

1

Article Tags :