What best practices should be followed when handling file uploads and database entries in PHP?
When handling file uploads and database entries in PHP, it is important to validate and sanitize user input to prevent security vulnerabilities such as SQL injection and file upload attacks. It is recommended to use prepared statements for inserting data into the database to prevent SQL injection. Additionally, when handling file uploads, ensure that only allowed file types are accepted and that uploaded files are stored in a secure location outside of the web root directory.
// Example of handling file upload and database entry in PHP
// Validate and sanitize file input
$allowedFileTypes = ['jpg', 'jpeg', 'png'];
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (in_array(pathinfo($uploadFile, PATHINFO_EXTENSION), $allowedFileTypes)) {
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);
// Sanitize user input before inserting into database
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
// Insert data into database using prepared statement
$stmt = $pdo->prepare("INSERT INTO users (name, file_path) VALUES (:name, :file_path)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':file_path', $uploadFile);
$stmt->execute();
} else {
echo "Invalid file type. Only JPG, JPEG, and PNG files are allowed.";
}