Php uses mb_check_encoding to check whether the string is valid in the specified encoding.
Source: Internet
Author: User
This article describes how to use mb_check_encoding in PHP to check whether the string is valid in the specified encoding. for example, mb_check_encoding-to check whether the string is valid in the specified encoding.
PHP version requirements: (PHP 4> = 4.4.3, PHP 5> = 5.1.3)
Bo: bool mb_check_encoding ([string $ var = NULL [, string $ encoding = mb_internal_encoding ()])
Check whether the specified byte stream is valid in the specified encoding. It effectively avoids the so-called "Invalid Encoding Attack )".
Parameters
Var
The byte stream to be checked. If this parameter is omitted, this function checks all input from the initial request.
Encoding
The expected encoding.
Return value
Returns TRUE if the call succeeds, or FALSE if the call fails.
To check whether a string is correctly encoded in utf-8, we recommend the following function to implement mb_check_encoding ():
The code is as follows:
Function check_utf8 ($ str ){
$ Len = strlen ($ str );
For ($ I = 0; $ I <$ len; $ I ++ ){
$ C = ord ($ str [$ I]);
If ($ c & gt; 128 ){
If ($ c> 247) return false;
Elseif ($ c & gt; 239) $ bytes = 4;
Elseif ($ c> 223) $ bytes = 3;
Elseif ($ c> 191) $ bytes = 2;
Else return false;
If ($ I + $ bytes)> $ len) return false;
While ($ bytes> 1 ){
$ I ++;
$ B = ord ($ str [$ I]);
If ($ B <128 | $ B> 191) return false;
$ Bytes --;
}
}
}
Return true;
} // End of check_utf8
?>
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.