Mb_check_encoding Check if the string is valid in the specified encoding

Source: Internet
Author: User
Tags ord

Ming: Bool Mb_check_encoding ([String $var = NULL [, String $encoding = Mb_internal_encoding ()]])
Checks whether the specified byte stream is valid in the specified encoding. It can effectively avoid the so-called "Invalid code attack (Invalid Encoding Attack)".

Parameters
Var
The byte stream to check. If this argument is omitted, this function checks all input from the original request.

Encoding

the desired encoding.

return value
Returns TRUE on success or FALSE on failure.


To check whether a string encoding is correct in utf-8, I recommend that the following function implement Mb_check_encoding ():

The code is as follows Copy Code


<?php
function Check_utf8 ($STR) {
$len = strlen ($STR);
for ($i = 0; $i < $len; $i + +) {
$c = Ord ($str [$i]);
if ($c > 128) {
if ($c > 247) return false;
ElseIf ($c > 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
?>

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.