How can the PHP 'move_uploaded_file' function help prevent file upload attacks?

File upload attacks can be prevented by using the PHP 'move_uploaded_file' function to move the uploaded file to a specified directory on the server. This function helps prevent attacks by ensuring that the uploaded file is stored in a safe location and not executed on the server.

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}