Current Location: Home> Latest Articles> Complete Guide to Uploading Files to PHP Server Root Directory

Complete Guide to Uploading Files to PHP Server Root Directory

M66 2025-10-20

How to Upload Files to the Root Directory in PHP

In PHP projects, sometimes it is necessary to upload files directly to the server root directory. This process mainly involves handling file uploads, validating file types, and generating unique file names.

Handle File Upload and Validate Types

<?php
// Specify allowed file types
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

// Upload file
if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
    // Get file type
    $fileType = $_FILES['file']['type'];

    // Check if file type is allowed
    if (!in_array($fileType, $allowedTypes)) {
        echo 'File type not allowed.';
        exit;
    }

    // Get file extension
    $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

    // Generate new file name (timestamp + random number)
    $newFileName = time() . '_' . rand(1, 999) . '.' . $extension;

    // Move file to root directory
    $uploadPath = getcwd() . '/' . $newFileName;
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);

    echo 'File uploaded successfully!';
} else {
    echo 'File upload failed.';
}
?>

HTML Form Example

On the front end, provide a file upload form:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

Conclusion

The above method allows you to safely upload files to the PHP server root directory. During the upload process, ensure file types are validated and use unique file names to prevent overwriting existing files. With a proper front-end form and back-end handling, file upload can be simple and efficient.