> ## Content Index
> Fetch the complete content index at: https://sudosecurity.org/llms.txt
> Use this file to discover other available public pages before exploring further.

# Strings Are Lying to You: Unicode Length, Case and Normalization in PHP, Python and JavaScript
- URL: https://sudosecurity.org/unicode-strings-php-python-javascript/
- Published: 2026-12-01T14:00:00.000Z
- Updated: 2026-12-01T14:00:00.000Z
- Description: One family emoji is 18 bytes, 8 JavaScript code units, 5 Python characters and 1 thing a human sees. I ran the same Unicode tests through PHP 8.6, Python 3.15 and Node 26: each gave a different answer for length, case and truncation, a KELVIN SIGN lowercases into a real username, and PHP 8.6's...
- Author: Santhdium
- Tags: Application Security, PHP, Python, JavaScript, Fundamentals, Web Applications, Programming Languages

Every web app has a username field, a 280-character limit somewhere, a "case-insensitive" lookup and a truncated preview. Each of those features rests on a question that sounds trivial: how long is this string, and are these two strings the same? It isn't trivial, and the three most common web languages each answer it differently by default.

Usually that's a cosmetic bug: a counter that's off by one, or a `�` at the end of a preview. Sometimes it's a security bug, like two accounts that collide, a reserved name that slips past a check, or an encoder that throws partway through a request. I ran the same set of strings through PHP 8.6.0, Python 3.15.2 and Node 26.13.1 to show exactly where each one gives a different answer.

## Unicode Strings in PHP, Python and JavaScript: Four Different Lengths

Six strings, chosen because each one breaks a different assumption:

```text
## PHP 8.6.0
              strlen  mb_strlen grapheme_strlen
ascii              5          5               5
cafe NFC           5          4               4
cafe NFD           6          5               4
thumbs+tone        8          2               1
family ZWJ        18          5               1
flag               8          2               1
## Python 3.15.2
             utf8 bytes  len()  graphemes
ascii                 5      5          5
cafe NFC              5      4          4
cafe NFD              6      5          4
thumbs+tone           8      2          1
family ZWJ           18      5          1
flag                  8      2          1
## Node v26.13.1
             utf8 bytes  .length  [...s]  Segmenter
ascii                 5        5       5          5
cafe NFC              5        4       4          4
cafe NFD              6        5       5          4
thumbs+tone           8        4       2          1
family ZWJ           18        8       5          1
flag                  8        4       2          1

```

| String                                             | UTF-8 bytes | JS .length | Code points (len(), mb\_strlen, \[...s\]) | Graphemes (what you see) |
| -------------------------------------------------- | ----------- | ---------- | ----------------------------------------- | ------------------------ |
| hello                                              | 5           | 5          | 5                                         | 5                        |
| café (é as one code point, NFC)                    | 5           | 4          | 4                                         | 4                        |
| café (e + combining accent, NFD)                   | 6           | 5          | 5                                         | 4                        |
| 👍🏽 thumbs up + skin tone                         | 8           | 4          | 2                                         | 1                        |
| Family emoji (man, woman, girl joined by two ZWJs) | 18          | 8          | 5                                         | 1                        |
| 🇺🇸 flag (two regional indicators)                | 8           | 4          | 2                                         | 1                        |

Four different units, all called "length":

- **Bytes.** What PHP's `strlen()` counts, what your database column limit may count, and what bcrypt's 72-byte limit counts.
- **UTF-16 code units.** What JavaScript's `.length` counts, because JS strings are UTF-16 internally. Anything outside the Basic Multilingual Plane, which includes every emoji, counts as 2.
- **Code points.** What Python's `len()`, PHP's `mb_strlen()` and JS's `[...s].length` count.
- **Grapheme clusters.** What a person sees as one character. You get these from PHP's `grapheme_strlen()` (intl), JS's `Intl.Segmenter`, or Python's third-party `regex` module with `\X`. **Python's standard library has no grapheme segmentation at all.**

If your UI says "20 characters max," grapheme clusters are the only honest unit. If your database says `VARCHAR(20)`, it means code points in MySQL's `utf8mb4` and in Postgres, so a 20-grapheme name made of family emoji needs 100 code points. Validate in the unit your storage actually enforces, and display in the unit your users see.

## Same Text, Different Bytes: Normalization

Both `café` strings above look identical and aren't equal in any of the three languages:

```text
"caf\u{E9}" === "cafe\u{301}"                false
...after Normalizer::FORM_C on both          true

```

The first is U+00E9, a single precomposed é. The second is `e` followed by U+0301, a combining acute accent. macOS file names, some keyboards and copy-paste from PDFs produce the second form. Normalizing both to NFC makes them equal, and all three languages can do it: `Normalizer::normalize()` (PHP intl), `unicodedata.normalize("NFC", s)` (Python), and `s.normalize()` (JavaScript, NFC by default).

The rule: **normalize once, at the input boundary**, before you store, hash, compare or index text. A unique index on unnormalized usernames lets two visually identical accounts exist side by side.

> **We recommend reading** [Building a Web Scraper in Python and PHP](https://sudosecurity.org/web-scraper-php-python/) to continue reading our selection of content. Scraped text is where every one of these encoding problems shows up at once, and this covers the scraping side in both languages.

[Building a Web Scraper in Python and PHP](https://sudosecurity.org/web-scraper-php-python/) The web holds a billion sites of unstructured data. How to pull it: requests, parsing, rate limits, and the legal line that scrapers actually live on. SudoSecurity · Santhdium

## Case Conversion: Three Languages, Four Answers

The full case-handling results:

```text
## PHP 8.6.0
ICU 76.1 (intl)
"caf\u{E9}" === "cafe\u{301}"                false
...after Normalizer::FORM_C on both          true
strtolower("\u{130}")  (Turkish dotted I)    "İ"
mb_strtolower("\u{130}")                     "i̇"
strtoupper("stra\u{DF}e")                    "STRAßE"
mb_strtoupper("stra\u{DF}e")                 "STRASSE"
mb_convert_case("stra\u{DF}e", MB_CASE_FOLD) "strasse"
mb_strtolower("\u{212A}elvin")  (KELVIN SIGN) "kelvin"
naive(Kelvin) / canon()                    ["Kelvin","kelvin"]
naive(ａｄｍｉｎ) / canon()             ["ａｄｍｉｎ","admin"]
naive(ADMİN) / canon()                      ["admİn","admi̇n"]
substr(..., 0, 4) is valid UTF-8             false
mb_substr(..., 0, 4)                         "café"
grapheme_substr(..., 0, 5)                   "café👍🏽"
## Python 3.15.2
Unicode data 17.0.0
"caf\u00e9" == "cafe\u0301"                  False
...after NFC on both                         True
"\u0130".lower()  (Turkish dotted I)         'i̇'
"stra\u00dfe".upper()                        'STRASSE'
"stra\u00dfe".casefold()                     'strasse'
"\u212aelvin".lower()  (KELVIN SIGN)         'kelvin'
naive('Kelvin') / canon()                    ('kelvin', 'kelvin')
naive('ａｄｍｉｎ') / canon()                     ('ａｄｍｉｎ', 'admin')
naive('ADMİN') / canon()                     ('admi̇n', 'admi̇n')
first 4 UTF-8 bytes of 'café...' decode      'caf�'
## Node v26.13.1
Unicode 17.0 ICU 78.3
"caf\u00e9" === "cafe\u0301"                 false
...after .normalize() on both                true
"\u0130".toLowerCase()  (Turkish dotted I)   "i̇"
"I".toLocaleLowerCase("tr")                  "ı"
"stra\u00dfe".toUpperCase()                  "STRASSE"
"\u212aelvin".toLowerCase()  (KELVIN SIGN)   "kelvin"
naive(Kelvin) / canon()                      ["kelvin","kelvin"]
naive(ａｄｍｉｎ) / canon()                       ["ａｄｍｉｎ","admin"]
naive(ADMİN) / canon()                       ["admi̇n","admi̇n"]
s.slice(0, 5).isWellFormed()                 false
encodeURIComponent(cut)                      "URIError: URI malformed"
Buffer.from(cut).toString()                  "café�"

```

What's worth knowing from that:

- **PHP's `strtolower()` and `strtoupper()` are ASCII-only.** Since PHP 8.2 they ignore locale and leave non-ASCII bytes alone, so `strtolower("İ")` returns `İ` unchanged and `strtoupper("straße")` returns `STRAßE`. That's predictable, but it's not Unicode case mapping. For that you need `mb_strtolower()` and `mb_strtoupper()`, which gave `STRASSE` like the other two languages.
- **Case folding exists in PHP and Python, but not in JavaScript.** `mb_convert_case($s, MB_CASE_FOLD)` and `str.casefold()` both turn `straße` into `strasse`, which is what you want for case-insensitive comparison. JS has `toLowerCase()` and the locale-aware `toLocaleLowerCase()`, which isn't the same thing. `"I".toLocaleLowerCase("tr")` gives Turkish dotless `ı`. That's correct for Turkish text, and a bug if a server locale changes your comparisons.
- **`İ` (U+0130, Turkish capital dotted I) lowercases to two code points**, `i` plus a combining dot above, in every Unicode-aware function. Case conversion can change a string's length.

## The Security Part: Usernames That Collide

The classic attack uses U+212A, the KELVIN SIGN. It looks like a capital K, and Unicode's case mapping lowercases it to an ordinary ASCII `k`. Python's `"Kelvin".lower()`, JavaScript's `.toLowerCase()` and PHP's `mb_strtolower()` all return the plain ASCII string `kelvin`.

So if signup checks uniqueness with one function and login looks up the user with another, two different strings can end up meaning the same account. Here's a reserved-name check, the kind that stops someone from registering `admin`:

```python
import unicodedata

RESERVED = {"admin", "root", "support"}

def canon(u: str) -> str:
    return unicodedata.normalize("NFKC", unicodedata.normalize("NFKC", u).casefold())

for name in ["admin", "Admin", "ａｄｍｉｎ", "Kelvin"]:
    naive_ok = name.lower() not in RESERVED
    canon_ok = canon(name) not in RESERVED
    print(f"{name!r:<14} lower()-check allows: {naive_ok!s:<5}  canon()-check allows: {canon_ok!s:<5}  stored as {canon(name)!r}")

```

```text
'admin'        lower()-check allows: False  canon()-check allows: False  stored as 'admin'
'Admin'        lower()-check allows: False  canon()-check allows: False  stored as 'admin'
'ａｄｍｉｎ'        lower()-check allows: True   canon()-check allows: False  stored as 'admin'
'Kelvin'       lower()-check allows: True   canon()-check allows: True   stored as 'kelvin'

```

The naive `lower()` check lets fullwidth `ａｄｍｉｎ` (U+FF41 and friends) straight through, because those aren't the ASCII letters in the reserved set. NFKC normalization maps fullwidth forms to ASCII, so the canonical check catches it and the stored name is `admin`. The fix is one canonicalization function, applied at every boundary: signup, login, password reset, admin lookups and uniqueness constraints. For identifiers, that's NFKC, then case fold, then NFKC again, which approximates Unicode's own NFKC\_Casefold mapping (the IETF's PRECIS framework, RFC 8265, is the standard to read if you need a full username profile). Then store the canonical form, or at least index on it.

JavaScript can't do this exactly, because it has no case fold. `normalize("NFKC")` plus `toLowerCase()` covers these cases (the Node output above shows `["kelvin","kelvin"]` and `["ａｄｍｉｎ","admin"]`), but `ß` stays `ß` instead of folding to `ss`. If a Node service and a Python service share a users table, decide on one canonicalization and do it in one place, ideally the database or a single shared service.

## The Database Has Its Own Opinion

Even if your application canonicalizes perfectly, the uniqueness constraint lives in the database, and the database has its own idea of "case-insensitive." SQLite is the easiest to test, since it ships inside Python, and it's the default database for a lot of prototypes, Laravel starters and Django tutorials:

```python
import sqlite3

db = sqlite3.connect(":memory:")
print("SQLite", sqlite3.sqlite_version)
db.execute("CREATE TABLE users (name TEXT NOT NULL UNIQUE COLLATE NOCASE)")
for name in ["admin", "ADMIN", "ａｄｍｉｎ", "Kelvin", "kelvin", "straße", "STRASSE", "Émile", "émile"]:
    try:
        db.execute("INSERT INTO users VALUES (?)", (name,))
        print(f"insert {name!r:<14} ok")
    except sqlite3.IntegrityError as e:
        print(f"insert {name!r:<14} rejected: {e}")
print("SELECT lower('ÉMILE') ->", db.execute("SELECT lower('ÉMILE')").fetchone()[0])

```

```text
SQLite 3.53.1
insert 'admin'        ok
insert 'ADMIN'        rejected: UNIQUE constraint failed: users.name
insert 'ａｄｍｉｎ'        ok
insert 'Kelvin'       ok
insert 'kelvin'       ok
insert 'straße'       ok
insert 'STRASSE'      ok
insert 'Émile'        ok
insert 'émile'        ok
SELECT lower('ÉMILE') -> Émile

```

`COLLATE NOCASE` stopped `ADMIN` from duplicating `admin` and let everything else through. `Émile` and `émile` became two different accounts, as did `straße` and `STRASSE`, and the KELVIN SIGN `Kelvin` and ASCII `kelvin`. SQLite's docs are explicit that its built-in `NOCASE` and `lower()` only fold ASCII. `lower('ÉMILE')` returned `Émile`, with the É untouched.

MySQL and Postgres differ again. MySQL's `utf8mb4` collations fold case with their own Unicode rules, and some also ignore accents. Postgres compares bytes unless you use `citext` or a nondeterministic ICU collation. So the same signup flow can enforce three different definitions of "the same username" depending on which database is underneath it. The fix is the one from the previous section, applied at the storage layer: store the canonical form in its own column with a plain unique index, and never rely on a collation to do your canonicalization for you.

> **We recommend reading** [Writing Your Own API From Scratch in TypeScript](https://sudosecurity.org/writing-your-own-api-from-scratch-in-typescript/) to continue reading our selection of content. Input validation is where canonicalization belongs, and this API build shows where that layer sits.

[Writing Your Own API From Scratch in TypeScript](https://sudosecurity.org/writing-your-own-api-from-scratch-in-typescript/) Build a production TypeScript API from scratch: authentication, validation, error handling, rate limiting, connection pooling, logging and tests. SudoSecurity · Santhdium

## Truncation: How to Cut a String in Half Wrong

The last block of tests cut `café👍🏽` at a fixed position:

| Language | Operation                                 | Result                                        |
| -------- | ----------------------------------------- | --------------------------------------------- |
| PHP      | substr($s, 0, 4) (bytes)                  | Invalid UTF-8: mb\_check\_encoding says false |
| PHP      | mb\_substr($s, 0, 4)                      | café                                          |
| PHP      | grapheme\_substr($s, 0, 5)                | café👍🏽, emoji and skin tone kept together   |
| Python   | s.encode()\[:4\].decode(errors="replace") | caf�                                          |
| JS       | s.slice(0, 5)                             | Lone surrogate: isWellFormed() is false       |
| JS       | encodeURIComponent(cut)                   | **URIError: URI malformed**                   |
| JS       | Buffer.from(cut).toString()               | café�                                         |

The JavaScript row is the one that takes down requests. `slice()` works on UTF-16 code units, so cutting at 5 splits the 👍 surrogate pair. The result is a malformed string that most of JS doesn't care about, until it hits `encodeURIComponent()`, which throws. A "truncate the title for the share URL" helper can 500 on the first emoji user. ES2024's `isWellFormed()` and `toWellFormed()` exist for exactly this. Better still, truncate on grapheme boundaries using `Intl.Segmenter`.

In PHP, the `substr()` cut produces invalid UTF-8 that `json_encode()` will refuse by default. In Python, the language makes it hard to split a code point, because `str` slicing works on code points. But slicing bytes and decoding with `errors="replace"` quietly turns data loss into `�`.

## The Deployment Surprise: PHP 8.6's Image Dropped mbstring

When I first ran the PHP tests on the official `php:8.6-cli` image, they died immediately:

```text
Fatal error: Uncaught Error: Call to undefined function mb_strlen()

```

The `php:8.5-cli` image includes `mbstring`. The 8.6 image doesn't. The docker-library 8.5 Dockerfile has `--enable-mbstring` with a comment explaining why it's compiled in, and the 8.6 Dockerfile has no such line. The likely reason is in PHP 8.6's UPGRADING notes: "Mbregex has been deprecated, because the underlying Oniguruma library is no longer maintained." Without Oniguruma, the image maintainers apparently stopped building mbstring by default.

My Laravel 13 benchmark from earlier in this series ran fine on that image anyway, because Laravel depends on `symfony/polyfill-mbstring`, a pure-PHP fallback that's much slower and quietly covers the gap. Your own code may not have it. If you move to `php:8.6-*`, add mbstring back explicitly. I used this in my test image (`intl` needs `libicu-dev` from apt first):

```text
docker-php-ext-configure mbstring --disable-mbregex && docker-php-ext-install intl bcmath mbstring

```

That's the command from my Dockerfile, minus my sandbox's proxy setup. The `--disable-mbregex` flag skips the deprecated regex functions, so you don't need Oniguruma.

## Unicode Versions Differ Too

Each runtime carries its own Unicode tables: Python 3.15.2 reported Unicode data 17.0.0, Node 26 reported Unicode 17.0 with ICU 78.3, PHP's intl was built against ICU 76.1, and PHP 8.6's UPGRADING notes say mbstring's tables "have been updated to Unicode 18.0." For characters assigned in the newest Unicode version, a Node service and a PHP service can disagree about case mapping, character properties or grapheme boundaries. That's rare, but it's another reason to canonicalize in exactly one place.

## What This Doesn't Cover

- **Homoglyph and confusable detection.** Cyrillic `а` versus Latin `a` survives NFKC unchanged. That needs UTS #39 confusable checks, which is its own topic.
- **Bidirectional text.** RTL override characters in file names and code reviews are a separate class of attack.
- **MySQL and Postgres collations.** I tested SQLite above. The server databases change equality and uniqueness in their own ways and need their own test.
- **Encodings other than UTF-8.** Legacy Shift-JIS and Windows-1252 data is out of scope.
- **Regex Unicode modes.** `/u` in PCRE and JS and Python's `re` Unicode semantics affect matching too. ReDoS gets its own article.

## The Actual Point

"Length" means four different things, and each language's default counts a different one: bytes in PHP, UTF-16 units in JS, code points in Python. None of them counts what users see. Strings that look identical can be different bytes, and different strings can lowercase to the same account name. Normalize at the input boundary, canonicalize identifiers with NFKC plus case folding in one place, count and cut on grapheme clusters for anything a human reads, and check that your PHP 8.6 image actually has mbstring before production tells you it doesn't.

*Sources: php.net's mbstring and intl documentation, the PHP 8.6 UPGRADING file in php-src, the docker-library/php 8.5 and 8.6 Dockerfiles, the Python `unicodedata` documentation, and the ECMAScript String and Intl.Segmenter specs. All tests were run by me on php:8.6-cli rebuilt with intl, bcmath and mbstring (ICU 76.1), Python 3.15.2 with the regex package, and node:26-slim. Every script and output block above is reproduced verbatim from those runs, except the one-line build command, which is quoted from my test Dockerfile without the sandbox's proxy lines.*