How can PHP beginners improve their file uploading code to avoid errors?

Beginners can improve their file uploading code by adding error handling to catch any issues that may arise during the process. They should also validate the file type and size before uploading it to the server to prevent potential security risks. Additionally, using unique file names and storing uploaded files in a secure directory can help avoid conflicts and unauthorized access.

// Check for errors during file upload
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    echo 'Error uploading file. Please try again.';
    exit;
}

// Validate file type and size
$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
$max_size = 5242880; // 5MB

if (!in_array($_FILES['file']['type'], $allowed_types) || $_FILES['file']['size'] > $max_size) {
    echo 'Invalid file type or size. Please upload a file less than 5MB in JPEG, PNG, or GIF format.';
    exit;
}

// Generate a unique file name and move the uploaded file to a secure directory
$upload_dir = 'uploads/';
$unique_filename = uniqid() . '_' . $_FILES['file']['name'];

if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir . $unique_filename)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file. Please try again.';
}