Find out the post data size in byte
When I submits the form in php. I want to find the size of the data for each text box that are posted through javascript in bytes.开发者_开发问答
The data the you will get are in elements that has "name" tag with, no matter how was the submit by user or by javascript function.
in php code you just take the posted data and check their size.
User gliff from webmasterworld.com says:
" that all depends on the character encoding. One ASCII character takes one byte to store. However, if you're dealing with multi-byte strings and/or Unicode, one character doesn't necessarily correspond to one byte.
I am/was hoping there's a built-in function I've overlooked that automatically takes all that into account and magically spits out a number. "
I thought its better to paste here and credit encase the page no longer exists.
Once you get your type, the built in function would be something like:
mb_strlen($utf8_string, 'latin1');
There are two options. For a byte count, use strlen:
$boxlen = strlen($_POST['field']);
For character length, if you have mb_string installed:
$boxlen = mb_strlen($_POST['field']);
Note, that if you have MBString function overloading on, the strlen()
won't be accurate. To check:
$mask = ini_get('mbstring.func_overload');
if (($mask & 2) === 2) {
//strlen is overloaded
}
If it is overloaded, and you want a byte count, you'll have to do something a little messy. Off the top of my head, the most "accurate" way I can think of would be something like:
function getByteCount($str) {
$mask = ini_get('mbstring.func_overload');
if (($mask & 2) === 2) {
//strlen is overloaded
return mb_strlen($str, 'latin1');
} else {
return strlen($str);
}
}
NOTE: That the mb_strlen()
method would only be needed if strlen()
is overridden by mb_string. Otherwise, it will work fine for byte length.
EDIT: Added () around the bit comparison (Needed because of operator order).
精彩评论