我製作了一個表格,用戶可以填寫它並檢查用戶是否正確插入電子郵件。'HTML文檔的字符編碼未聲明'問題
- 如果返回false:用戶會看到一條錯誤消息。
- 如果它返回true:它會向用戶顯示一條確認消息,但它也會將數據寫入數據庫。
因此,當我試圖在PHP文件中添加表單時,發生了問題,因此我可以發出警報或在同一頁上給用戶提供錯誤消息。我開始收到此錯誤:
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
所以我試圖恢復到舊版本還原此,我不得不剪切和粘貼代碼,但沒有太複雜了幾件。出於一些奇怪的原因,我仍然得到這個錯誤。當然,我在Stackoverflow上查看了這個問題上的類似主題,但沒有任何答案讓我更進一步。例如,在頁面的標題中添加meta
信息,我還創建了一個如下所示的PHP標頭:header('Content-type: text/html; charset=utf-8');
之後,我閱讀了一些關於此錯誤的文章,但沒有人幫助我解決此問題。
這是我的代碼的一個例子。這是我得到的錯誤:
<?php
include_once('credentials.php');
mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
include_once('functions.php');
$apples = sanitize($_POST['Apple']);
$oranges = sanitize($_POST['Orange']);
$melons = sanitize($_POST['Melon']);
$pears = sanitize($_POST['Pear']);
$strawberries = sanitize($_POST['Strawberry']);
$grapes = sanitize($_POST['Grape']);
if($_POST['Grape'] == 'Yes')
{ $grapes = 1; }
else
{ $grapes = 0; }
$blueberries = sanitize($_POST['Blueberry']);
if (checkStrawberries($strawberries) == true) {
mysql_query(" INSERT INTO tablename (Name, Weight, Color, Ripeness, Age, Origin, Destination)
VALUES ('$apples', '$oranges', '$melons', '$Pears', '$strawberries', '$grapes', '$blueberries') ");
or die(mysql_error());
echo '<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
</head>
<title>Page</title>
<body>
True
<a href="../index.php">home</a>
</body>
</html>';
} else {
echo '<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
</head>
<title>Pagina</title>
<body>
False
<a href="../index.php">home</a>
</body>
</html>';
}
?>
我不得不重新命名變量和類,因爲它們與我工作的公司有很強的關係。
編輯:這個錯誤是由使用Firebug的Firefox日誌控制檯產生的。
編輯2:更改了var和函數名稱以避免混淆並說明此應用程序中的數據交換。
編輯3:我試圖弄清楚在我的代碼中究竟產生了這個錯誤,因爲我測試了編碼部分,下面給出了Dobromir Velev向我提供的測試用例,並且工作得很好。我決定評論出IF ELSE聲明,但我沒有得到任何錯誤。所以這似乎破壞了頁面。
我現在刪除了回聲,因爲它沒有給這個特定的挑戰添加任何值。
if (checkStrawberries($strawberries) == true) {
mysql_query("INSERT INTO tablename (Name, Weight, Color, Ripeness, Age, Origin, Destination)
VALUES ('$apples', '$oranges', '$melons', '$Pears', '$strawberries', '$grapes', '$blueberries') ");
or die(mysql_error());
} else {
echo 'FALSE';
}
功能checkStrawberries是這樣的:
function checkEmail($email) {
if (!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-] +)+$/" , $email)) {
return false;
}
return true;
}
功能sanitize方法是這樣的:
function sanitize($dirty){
$clean = htmlspecialchars($dirty);
$cleaner = mysql_real_escape_string($clean);
return $cleaner;
}
你究竟在哪裏看到那條消息,它是什麼產生的? – deceze
我希望你沒有真正將函數命名爲'function'? ('函數($ _ POST [ '1']);')。這可能會弄亂一些代碼,因爲'function'是一個保留關鍵字。 – Jelmer
@deceze檢查編輯。 –