Current Location: Home> Latest Articles> How to check the existence of a directory with is_dir function when uploading a file

How to check the existence of a directory with is_dir function when uploading a file

gitbox 2025-05-28

1. Basic usage

The syntax of is_dir() is very simple:

 bool is_dir(string $filename)

It accepts a string parameter $filename , returning a boolean value. Return true if the path exists and is a directory; otherwise return false .


2. Examples of uploading and using it in combination with file

Suppose we want to save the uploaded file to the uploads/documents/ directory, we need to check whether the directory exists before uploading the file:

 <?php
$uploadDir = 'uploads/documents/';

if (!is_dir($uploadDir)) {
    // If the directory does not exist,Just try to create it
    if (!mkdir($uploadDir, 0755, true)) {
        die('Unable to create upload directory');
    }
}

// Process file upload
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $tmpName = $_FILES['file']['tmp_name'];
    $filename = basename($_FILES['file']['name']);
    $destination = $uploadDir . $filename;

    if (move_uploaded_file($tmpName, $destination)) {
        echo 'File upload successfully:' . htmlspecialchars($destination);
    } else {
        echo 'File movement failed';
    }
} else {
    echo 'An error occurred during upload';
}
?>

The key to this code is:

  1. Use is_dir() to check whether the target upload directory exists.

  2. If it does not exist, then use mkdir() to create the directory recursively.

  3. After the file is uploaded successfully, use move_uploaded_file() to move the temporary file to the target directory.


3. Path specification suggestions in actual projects

In actual projects, we can also combine __DIR__ or $_SERVER['DOCUMENT_ROOT'] to build a more robust path to avoid problems caused by relative paths:

 $uploadDir = __DIR__ . '/uploads/documents/';

or:

 $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/documents/';

4. Combination with URL (front-end display)

After the upload is successful, we may need to return the URL of the file to the front end. Assuming that the domain name of our server is gitbox.net , you can splice the file address like this:

 $fileUrl = 'https://gitbox.net/uploads/documents/' . urlencode($filename);
echo 'File uploaded,Access address:<a href="' . $fileUrl . '">' . $fileUrl . '</a>';

In this way, users can directly access the uploaded file through the URL.