What best practices should be followed when handling file uploads in PHP to prevent errors and ensure successful uploads?

When handling file uploads in PHP, it is important to set the appropriate configuration options, validate the file type and size, sanitize the file name, and move the uploaded file to a secure directory. By following these best practices, you can prevent errors and ensure successful file uploads.

// Set configuration options
ini_set('upload_max_filesize', '2M');
ini_set('post_max_size', '8M');

// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 2 * 1024 * 1024; // 2MB

if (!in_array($_FILES['file']['type'], $allowedTypes) || $_FILES['file']['size'] > $maxSize) {
    die('Invalid file type or size.');
}

// Sanitize file name
$fileName = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);

// Move uploaded file to secure directory
$uploadDir = 'uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir);
}

$uploadPath = $uploadDir . $fileName;
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}