Why is it recommended to use move_uploaded_file function for file uploads in PHP?

Using the move_uploaded_file function in PHP is recommended for file uploads because it helps prevent security vulnerabilities such as directory traversal attacks. This function ensures that uploaded files are moved to a specified directory on the server, rather than executing them in their temporary location, which could potentially be exploited by malicious users.

<?php
$upload_dir = 'uploads/';
$uploaded_file = $_FILES['file']['tmp_name'];
$target_file = $upload_dir . basename($_FILES['file']['name']);

if (move_uploaded_file($uploaded_file, $target_file)) {
    echo "File uploaded successfully.";
} else {
    echo "Error uploading file.";
}
?>