What are potential pitfalls when using move_uploaded_file function in PHP for file uploads?

One potential pitfall when using the move_uploaded_file function in PHP for file uploads is not properly validating the file before moving it to the desired location. This can lead to security vulnerabilities such as allowing malicious files to be uploaded and executed on the server. To prevent this, always validate the file type, size, and content before moving it using move_uploaded_file.

// Example of validating file before moving it using move_uploaded_file

$uploadDir = 'uploads/';
$allowedTypes = ['image/jpeg', 'image/png'];
$maxFileSize = 5 * 1024 * 1024; // 5 MB

if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileType = $_FILES['file']['type'];
    $fileSize = $_FILES['file']['size'];

    if (in_array($fileType, $allowedTypes) && $fileSize <= $maxFileSize) {
        $tempFile = $_FILES['file']['tmp_name'];
        $newFile = $uploadDir . $_FILES['file']['name'];

        if (move_uploaded_file($tempFile, $newFile)) {
            echo 'File uploaded successfully!';
        } else {
            echo 'Error uploading file.';
        }
    } else {
        echo 'Invalid file type or size.';
    }
} else {
    echo 'Error uploading file.';
}