What are some best practices for handling file uploads in PHP functions?
When handling file uploads in PHP functions, it is important to validate the file type, size, and ensure secure file storage to prevent security risks such as file injection attacks. One best practice is to use PHP's built-in functions like `move_uploaded_file()` to move the uploaded file to a secure location on the server. Additionally, sanitizing file names and using unique file names can help prevent conflicts and maintain organization.
<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
// Validate file type
$file_type = pathinfo($file_name, PATHINFO_EXTENSION);
if($file_type != 'jpg' && $file_type != 'png' && $file_type != 'jpeg'){
echo "Only JPG, JPEG, PNG files are allowed.";
exit;
}
// Validate file size (max 5MB)
if($file_size > 5*1024*1024){
echo "File size must be less than 5MB.";
exit;
}
// Move uploaded file to desired directory
$upload_path = 'uploads/';
$new_file_name = uniqid().'.'.$file_type;
if(move_uploaded_file($file_tmp, $upload_path.$new_file_name)){
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
} else {
echo "Error uploading file.";
}
?>