What are best practices for setting the charset in both the HTTP-Content-Type and DB-Connection in PHP?

When working with character encoding in PHP, it is important to ensure consistency between the charset specified in the HTTP Content-Type header and the charset used in the database connection. This helps prevent issues with data corruption or incorrect character display. To set the charset in both places, you can use the header() function to set the charset in the Content-Type header and specify the charset in the DSN string when establishing a database connection.

// Set charset in HTTP Content-Type header
header('Content-Type: text/html; charset=utf-8');

// Establish database connection with charset specified
$dsn = 'mysql:host=localhost;dbname=mydatabase;charset=utf8';
$username = 'username';
$password = 'password';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

try {
    $dbh = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}