What are the best practices for configuring PHP scripts and databases to support UTF-8 encoding, especially in the context of web applications like online shops?

When working with web applications like online shops, it is crucial to configure PHP scripts and databases to support UTF-8 encoding to ensure proper handling of multilingual content. To achieve this, make sure to set the character set to UTF-8 in both PHP scripts and database connections. Additionally, use prepared statements or parameterized queries to prevent SQL injection attacks and ensure data integrity.

// Set UTF-8 encoding in PHP scripts
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');

// Connect to the database with UTF-8 encoding
$dsn = 'mysql:host=localhost;dbname=your_database;charset=utf8';
$username = 'your_username';
$password = 'your_password';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);

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