What best practices should be followed when handling file uploads and processing form data in PHP?
When handling file uploads and processing form data in PHP, it is important to validate and sanitize the input to prevent security vulnerabilities such as file injection and cross-site scripting attacks. Use built-in PHP functions like move_uploaded_file() to securely move uploaded files to a designated directory. Additionally, always use prepared statements or parameterized queries when interacting with a database to prevent SQL injection attacks.
// Example of handling file upload and processing form data in PHP
// Validate and sanitize form data
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
// Handle file upload
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
// Use prepared statements to insert data into database
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();