PHP 8.5.0 Alpha 1 available for testing

Voting

: min(nine, four)?
(Example: nine)

The Note You're Voting On

joeri at sebrechts dot net
8 years ago
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);
?>

<< Back to user notes page

To Top