What are some best practices for handling file uploads in PHP scripts to avoid errors like file not found or directory permission issues?

When handling file uploads in PHP scripts, it is important to ensure that the file exists and that the directory where the file will be saved has the correct permissions set. To avoid errors like "file not found" or directory permission issues, you can use PHP's built-in functions like `file_exists()` and `is_writable()` to check if the file and directory are accessible before uploading.

// Check if the file exists
if (!file_exists($_FILES['file']['tmp_name'])) {
    die("File not found.");
}

// Check if the directory is writable
$uploadDir = 'uploads/';
if (!is_writable($uploadDir)) {
    die("Directory is not writable.");
}

// Move the uploaded file to the directory
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
    echo "File uploaded successfully.";
} else {
    echo "Error uploading file.";
}