How can PHP developers improve the efficiency and security of file uploads by utilizing built-in PHP functions like move_uploaded_file and getimagesize?

When handling file uploads in PHP, developers can improve efficiency and security by using built-in functions like move_uploaded_file to securely move uploaded files to a designated directory and getimagesize to validate uploaded images. By properly utilizing these functions, developers can prevent common security vulnerabilities like arbitrary code execution and file path traversal attacks.

// Example code snippet to handle file uploads securely using move_uploaded_file and getimagesize

// Check if file was uploaded successfully
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    // Validate file type and size
    $allowedTypes = ['image/jpeg', 'image/png'];
    $maxSize = 1048576; // 1MB

    if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
        // Move uploaded file to designated directory
        $uploadDir = 'uploads/';
        $uploadFile = $uploadDir . basename($_FILES['file']['name']);

        if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
            // File upload successful
            echo 'File uploaded successfully.';
        } else {
            // File upload failed
            echo 'Failed to upload file.';
        }
    } else {
        // Invalid file type or size
        echo 'Invalid file type or size.';
    }
} else {
    // Error handling for file upload
    echo 'Error uploading file.';
}