mysqli_set_charset($link, 'utf8mb4') 或 PDO DSN 加 charset=utf8mb4header("Content-Type: text/html; charset=utf-8");CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci<?php
header("Content-Type: text/html; charset=utf-8");
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8mb4';
$pdo = new PDO($dsn, 'root', '', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// 測試寫入中文
$stmt = $pdo->prepare("INSERT INTO posts (title, content) VALUES (?, ?)");
$stmt->execute(['測試標題', '中文內容測試 😀']);
echo '寫入成功,無亂碼';
$mysqli = new mysqli('localhost', 'root', '', 'test');
$mysqli->set_charset('utf8mb4'); // 關鍵!
$stmt = $mysqli->prepare("INSERT INTO posts (title, content) VALUES (?, ?)");
$stmt->bind_param('ss', $title, $content);
$title = '測試標題';
$content = '中文內容測試';
$stmt->execute();
| 錯誤做法 | 正確做法 |
|---|---|
mysql_query("SET NAMES utf8") | 用 mysqli_set_charset() 或 PDO DSN charset 參數 |
資料表用 utf8 | 用 utf8mb4(支援 Emoji、生僻字) |
| PHP 檔案存成 ANSI/Big5 | 編輯器另存為 UTF-8 無 BOM |
| 只設 header() 不設連線字元集 | 兩者必須同時設定 |
function checkIP($ip) {
$deny = [
'192.168.1.1', // 單一 IP
'192.168.1.*', // 萬用字元
'192.168.1.1-20', // 範圍
'192.168.1.[1|2|3]', // 列舉
];
// 實作略...
}
建議使用成熟函式庫(如 symfony/http-foundation 的 IpUtils)處理 CIDR、範圍比對。
原始來源:www.111cn.net