How can PHP developers optimize their code to prevent errors and improve the reliability of file upload functionality on their websites?

To optimize their code and improve the reliability of file upload functionality, PHP developers can implement proper error handling, validate file types and sizes, and secure file uploads by storing them in a designated directory outside the web root.

// Set upload directory outside web root
$uploadDirectory = '/path/to/upload/directory/';

// Check for errors during file upload
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    die('File upload failed with error code: ' . $_FILES['file']['error']);
}

// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png'];
$allowedSize = 1048576; // 1MB

if (!in_array($_FILES['file']['type'], $allowedTypes) || $_FILES['file']['size'] > $allowedSize) {
    die('Invalid file type or size. Please upload a JPEG or PNG file under 1MB.');
}

// Move uploaded file to designated directory
$uploadedFilePath = $uploadDirectory . $_FILES['file']['name'];
if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFilePath)) {
    die('Failed to move uploaded file.');
}

echo 'File uploaded successfully.';