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 .
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:
Use is_dir() to check whether the target upload directory exists.
If it does not exist, then use mkdir() to create the directory recursively.
After the file is uploaded successfully, use move_uploaded_file() to move the temporary file to the target directory.
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/';
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.