Skip to content
PHP Logo

In what ways can PHP developers optimize the code for displaying user-generated content, such as news articles, while ensuring data integrity and security?

To optimize the code for displaying user-generated content like news articles while ensuring data integrity and security, PHP developers can sanitize user input to prevent SQL injection attacks, validate and filter user input to prevent XSS attacks, and use prepared statements for database queries. Additionally, developers can implement proper error handling to catch and handle any potential issues that may arise.

php
// Sanitize user input to prevent SQL injection
$userInput = mysqli_real_escape_string($conn, $_POST['user_input']);

// Validate and filter user input to prevent XSS attacks
$userInput = htmlspecialchars($_POST['user_input']);

// Use prepared statements for database queries
$stmt = $conn->prepare("SELECT * FROM news_articles WHERE title = ?");
$stmt->bind_param("s", $userInput);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Display news article content
}

// Implement proper error handling
if (!$result) {
    die('Error: ' . $conn->error);
}