What are some best practices for handling file uploads and storing file names in a PHP application?
When handling file uploads in a PHP application, it is important to validate the file type and size to prevent security vulnerabilities. Additionally, generating unique file names to avoid overwriting existing files is crucial. Storing the file names in a secure location, such as a database, can help keep track of uploaded files.
// Handle file upload
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$file_name = uniqid() . '_' . $_FILES['file']['name'];
$target_dir = "uploads/";
$target_file = $target_dir . $file_name;
// Validate file type and size
$allowed_types = array('jpg', 'png', 'pdf');
$file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (in_array($file_extension, $allowed_types) && $_FILES['file']['size'] < 5000000) {
move_uploaded_file($_FILES['file']['tmp_name'], $target_file);
// Store file name in database
$stmt = $pdo->prepare("INSERT INTO files (file_name) VALUES (?)");
$stmt->execute([$file_name]);
} else {
echo "Invalid file type or size.";
}
}