In the context of PHP web development, what are the recommended methods for handling external content to maintain code integrity and security?

When handling external content in PHP web development, it is important to sanitize and validate inputs to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. One recommended method is to use prepared statements for database queries and filter user inputs using functions like htmlentities() or htmlspecialchars(). Additionally, it is crucial to validate and sanitize any data retrieved from external APIs or sources before processing or displaying it on the website.

// Example of using prepared statements to handle external content securely

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);

// Execute the statement
$stmt->execute();

// Fetch the results
$result = $stmt->fetch(PDO::FETCH_ASSOC);

// Sanitize and display the retrieved data
echo htmlentities($result['username']);