note 119650 added to function.strlen
| From: | joeri at sebrechts dot net | Date: | Tue, 26 Jul 2016 08:26:33 +0000 |
| Subject: | note 119650 added to function.strlen | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-206101@lists.php.net to get a copy of this message | ||
When checking for length to make sure a value will fit in a database field, be mindful of using the
right function.
There are three possible situations:
1. Most likely case: the database column is UTF-8 with a length defined in unicode code points (e.g.
mysql varchar(200) for a utf-8 database).
<?php
// ok if php.ini default_charset set to UTF-8 (= default value)
mb_strlen($value);
iconv_strlen($value);
// always ok
mb_strlen($value, "UTF-8");
iconv_strlen($value, "UTF-8");
// BAD, do not use:
strlen(utf8_decode($value)); // breaks for some multi-byte characters
grapheme_strlen($value); // counts graphemes, not code points
?>
2. The database column has a length defined in bytes (e.g. oracle's VARCHAR2(200 BYTE))
<?php
// ok, but assumes mbstring.func_overload is 0 in php.ini (= default value)
strlen($value);
// ok, forces count in bytes
mb_strlen($value, "8bit")
?>
3. The database column is in another character set (UTF-16, ISO-8859-1, etc...) with a length
defined in characters / code points.
Find the character set used, and pass it explicitly to the length function.
<?php
// ok, supported charsets: http://php.net/manual/en/mbstring.supported-encodings.php
mb_strlen($value, $charset);
// ok, supported charsets: https://www.gnu.org/software/libiconv/
iconv_strlen($value, $charset);
?>
----
Server IP: 72.52.91.14
Probable Submitter: 81.246.42.197
----
Manual Page -- http://php.net/manual/en/function.strlen.php
Edit -- https://master.php.net/note/edit/119650
Del: integrated -- https://master.php.net/note/delete/119650/integrated
Del: useless -- https://master.php.net/note/delete/119650/useless
Del: bad code -- https://master.php.net/note/delete/119650/bad+code
Del: spam -- https://master.php.net/note/delete/119650/spam
Del: non-english -- https://master.php.net/note/delete/119650/non-english
Del: in docs -- https://master.php.net/note/delete/119650/in+docs
Del: other reasons-- https://master.php.net/note/delete/119650
Reject -- https://master.php.net/note/reject/119650
Search -- https://master.php.net/manage/user-notes.php