Skip to content
PHP Logo

What are the best practices for handling file uploads and creating directories in PHP, especially in situations where safe mode restrictions are in place?

When handling file uploads and creating directories in PHP, especially in situations where safe mode restrictions are in place, it is important to ensure that the directories are created with appropriate permissions and that uploaded files are properly validated and sanitized to prevent security vulnerabilities.

php
// Ensure that the upload directory exists and has the correct permissions
$uploadDir = 'uploads/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// Handle file upload
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileName = basename($_FILES['file']['name']);
    $filePath = $uploadDir . $fileName;
    
    if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
} else {
    echo 'Error: ' . $_FILES['file']['error'];
}