回到一個問題,我相信你們會發現很容易解決。在 html 中使用 maxlength 函式時,我注意到用戶可以簡單地使用檢查元素來修改 maxlength 認為它非常無用。
最大長度的基本示例:
<input type="text" name="username" maxlength="250" alt="Please don't change my maxlength">
我正在尋找 Javascript 或 PHP 中的解決方案,以防止在服務器端進行這種代碼操作。
提前致謝。
uj5u.com熱心網友回復:
嘗試在 JS 中解決此問題是沒有意義的,因為用戶可以簡單地繞過您的驗證代碼并手動將表單提交到您的站點,該表單的值比指定的maxlength
. 所以你需要在PHP中處理它:
$username = $_POST['username'] ?? '';
if (strlen($username) > 250) {
// return some sort of error to the user
exit;
}
uj5u.com熱心網友回復:
對于 JavaScript 端,您可以設定一個MutationObserver
以防止maxlength
被更改。
請記住,這不是萬無一失的,只會增加難度。用戶可能會更改請求以更改發送到服務器的內容。因此,您可能還想在服務器端驗證資料。
[...document.querySelectorAll('input[maxlength]')].forEach(input => {
const originalMaxLength = input.getAttribute('maxlength');
new MutationObserver((mutations, observer) => {
const mutation = mutations.find(({ attributeName }) => attributeName.toLowerCase() === 'maxlength');
if(mutation && originalMaxLength !== input.getAttribute('maxlength')) {
console.log('maxlength has been changed, restoring...');
input.setAttribute('maxlength', originalMaxLength);
}
}).observe(input, { attributes: true });
})
<h2>Try inspect and change maxlength</h2>
<input type="text" name="username" maxlength="250" alt="Please don't change my maxlength">
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/504365.html
標籤:javascript php html 最长长度
下一篇:我無法解決jsdiv隱藏問題