Are there any security considerations or best practices to keep in mind when enabling file uploads in PHP scripts?

When enabling file uploads in PHP scripts, it is important to consider security risks such as file upload vulnerabilities, potential file execution, and file size limitations. To mitigate these risks, it is recommended to validate file types, check file sizes, and store uploaded files in a secure directory outside the web root.

// Ensure file uploads are enabled in php.ini
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['uploaded_file'])) {
    $uploadDir = '/path/to/upload/directory/';
    
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    $maxFileSize = 1048576; // 1MB
    
    $fileType = $_FILES['uploaded_file']['type'];
    $fileSize = $_FILES['uploaded_file']['size'];
    $tmpFilePath = $_FILES['uploaded_file']['tmp_name'];
    
    if (in_array($fileType, $allowedTypes) && $fileSize <= $maxFileSize) {
        $newFilePath = $uploadDir . basename($_FILES['uploaded_file']['name']);
        
        if (move_uploaded_file($tmpFilePath, $newFilePath)) {
            echo 'File uploaded successfully.';
        } else {
            echo 'Error uploading file.';
        }
    } else {
        echo 'Invalid file type or size.';
    }
}