What are some best practices for handling file uploads in PHP to prevent uploading of inappropriate content?

When handling file uploads in PHP, it is important to implement security measures to prevent the uploading of inappropriate content such as malicious files or files with inappropriate content. One way to do this is by validating the file type and size before allowing the upload to proceed. Additionally, it is recommended to store uploaded files outside of the web root directory to prevent direct access to them.

// Validate file type and size before allowing upload
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxSize = 10 * 1024 * 1024; // 10MB

if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
    // Store uploaded file outside of web root directory
    $uploadDir = '/path/to/uploaded/files/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
} else {
    echo 'Invalid file type or size.';
}