`mb_detect_encoding()` detects UTF-8 emoji byte sequence as ISO-8859-1 since PHP 8.1
Description
I have a piece of code that tries to normalise the encoding of incoming strings using mb_detect_encoding(). While upgrading to PHP 8.1, I've noticed that a test which ensures that an urlencoded UTF-8 sequence (party hat emoji) now fails. It all comes down to a behaviour change of mb_detect_encoding() when passing UTF-8 and ISO-8859-1 (in which ever order) as $encodings in PHP 8.1.
I know that the way this method works (or the way that determining the enconding of a string works at all) can not be 100% realiable, so I'd also agree on not classifying this as a bug. However, it is an undocumented behaviour change introduced in 8.1 that might break existing code as it did with mine.
I assume that this change has been introduced with 28b346bc.
Example
See https://3v4l.org/RgdfE
<?php
echo mb_detect_encoding('🥳', ['UTF-8', 'ISO-8859-1']);
Resulted in this output:
ISO-8859-1
But I expected this output instead:
UTF-8
PHP Version
8.1.1
Operating System
No response
Hi, @filecage, and thanks for much for this report. Hope to look into it very soon.
Hmm. One point to start:
Legacy versions of PHP return UTF-8, not because they are smart enough to tell that the string is actually UTF-8 text, but because you put UTF-8 first in the list of candidate encodings. If you put ISO-8859-1 first, then all versions return ISO-8859-1.
The string is actually valid under both encodings; if interpreted as ISO-8859-1, it's an accented "o", followed by an accented "Y", followed by a Yen sign, followed by a superscript digit 3. A funny combination, but not invalid.
The current detection code treats all codepoints higher than U+FFFF as "rare", and penalizes candidate encodings under which the string contains such codepionts. That is what is making it prefer ISO-8859-1 over UTF-8.
@nikic Do you think I need to teach it that some emoji over U+FFFF are not "rare"?
Another point... no matter what we do, encoding detection will always be very, very unreliable for short strings. If you want to auto-detect text encoding with any level of reliability, you really need to give it more input text to work with.
Even so, let us think a bit about this issue of emoji. It is a fact that some emoji are used by a lot of people, and they do occupy ranges of Unicode codepoints over U+FFFF.
Thanks a lot @alexdowad for looking into this!
Legacy versions of PHP return UTF-8, not because they are smart enough to tell that the string is actually UTF-8 text, but because you put UTF-8 first in the list of candidate encodings. If you put ISO-8859-1 first, then all versions return ISO-8859-1.
When I saw that the output was different, I did not think that previous versions might be accidentally returning the correct results.
Even so, let us think a bit about this issue of emoji. It is a fact that some emoji are used by a lot of people, and they do occupy ranges of Unicode codepoints over U+FFFF.
I haven't yet had a chance to look deeply into it but I could imagine that if we're somehow able to reliably detect emojis in a string, it's a very strong indicator for a string to be UTF-8, even for short strings. It might not be worth the effort though.
I have the same problem, if text starts with emoji, it's not detected as UTF-8 (I am using Docker php:8.1.6-fpm)
I have a smiliar problem too, with a custom test suit in PhpUnit that throw us an error.
The test check if mb_detect_encoding find the correct encoding with an UTF-8 file content, with a BOM header.
You can see the simplify test here : https://3v4l.org/83vWZ
The problem is present in php 8.1 and 8.2 too.
@titanz35's problem has nothing to do with emoji; rather, it's about detecting encoding for strings which use a BOM. I have just prepared a fix for that.
@filecage, I am just amending mb_detect_encoding so it accepts the most basic emoji like "smiling face" and "frowning face". But I have seen that your test case is actually U+1F973 FACE WITH PARTY HORN AND PARTY HAT.
Do you think that qualifies as a 'common' and thus expected character to be found in input strings for mb_detect_encoding?
@alexdowad according to unicode, U+1F973 is categorized as basic emoji: https://unicode.org/Public/emoji/15.0/emoji-sequences.txt
When it comes to what I'd expect from mb_detect_encoding(), I would probably go with: either all or nothing. I know that that's a tough one, but I assume that people (including myself) won't expect mb_detect_encoding() to work with with some, but not all.
Just out of personal interest, what would be a good reason not to include all unicode standardized emojis? Is it that it would slow down the detection itself or that we have no reliable way of having an exhaustive list of existing emojis? Or is it something else?
@filecage The reason would be both to keep the detection code tight and fast and also to reduce the chances of wrongly detecting some random byte sequence as 'emoji'.
@filecage Thanks for sharing that link. The file states that there are 1386 'basic emoji'. Hmm... That's about 1% of the space from U+0000 up to U+1FFFF.
When it comes to what I'd expect from
mb_detect_encoding(), I would probably go with: either all or nothing. I know that that's a tough one, but I assume that people (including myself) won't expectmb_detect_encoding()to work with with some, but not all.
Thanks for sharing those thoughts.
Here's the thing: "detecting" the encoding of some random string of bytes which one finds on the Internet is actually impossible. (mb_detect_encoding is a misnomer; it should have been called mb_guess_encoding.) The process is entirely probabilistic, and we can only ever say that this sequence of bytes looks more likely to be a UTF-8 string than a ISO-8859-1 string, or vice versa.
Given that fact, if we see that a sequence of bytes decodes to U+1F600 GRINNING FACE in one possible text encoding, but decodes to U+1F9FF NAZAR AMULET in another possible text encoding, would it really make sense to say that both choices are "equally likely"? (Both are included in the list of "basic emoji"!)
If we wanted to make mb_detect_encoding smarter, we could teach it that this codepoint is in the top 100 most commonly used, but that one is only in the top 10,000. The biggest obstacle to doing this right now is that we would need a good corpus of text (in various languages) to derive the frequencies from. For the moment, we have just divided the entire body of all Unicode codepoints into two categories: "rare" and "common" (1 bit of information per codepoint).
I think there may be another misunderstanding here, and I have probably contributed to it. You talked about mb_detect_encoding "working with some, but not all" emoji, but to describe the function as "working" or "not working" on such characters is not really accurate. Currently, mb_detect_encoding's heuristics cause it to treat strings containing emoji as "less likely" than those not containing emoji, but if all other possible interpretations of the same bytes are even more unlikely, then mb_detect_encoding will pick the emoji.
For example, please see https://3v4l.org/gVQXJ.
<?php
echo mb_detect_encoding("🥳", ['UTF-32BE', 'UTF-16BE', 'UTF-16LE', 'UTF-8', 'SJIS', 'EUC-KR', 'BIG-5']), "\n";
For your test case, the reason why mb_detect_encoding picks ISO-8859-1, is because 1) the string is actually valid in ISO-8859-1, and 2) it decodes entirely to "common" codepoints under that interpretation.
(As it turns out, encoding detection is extremely problematic when the ISO-8859-X encodings are involved. That is because the strongest signal which helps us to "detect" the correct encoding is when the input bytes do not form a valid string in most of the candidate encodings. However, every sequence of bytes is always a valid string in ISO-8859-1, so our strongest test is completely ineffective.)
Hopefully all of this helps you understand that the answer is not "all or nothing". We still do need to determine what emoji are more likely to appear in mb_detect_encoding's input, and which are less likely to appear. I strongly feel that some of the "basic" emoji, like U+1F316 WANING GIBBOUS MOON, should be deemed less likely.
@filecage ...So we still come back to the question of U+1F973 should be on our "common" list, and I guess your answer is probably "yes"...
I should have mentioned, you can find this list in ext/mbstring/common_codepoints.txt, in the PHP source tree.
I have some of the same issues. But find it hard to reason out, why/when the function returns what I want and when it does not.
I get that the old way was broken, but why/when mb_detect_encoding returns UTF-8 or not in the two cases here is beyond me.
This is mixed, but would expect UTF-8. (https://3v4l.org/96Wl1)
$text = 'abcde æøå æøå ð Ð ≗ 䎇 顃 ‰';
echo mb_detect_encoding($text, ['UTF-8', 'CP1252', 'ISO-8859-1'], true);
Do I remove the last ‰ from the text, the detection returns UTF-8 in all versions. (https://3v4l.org/Y7BQH)
$text = 'abcde æøå æøå ð Ð ≗ 䎇 顃 ‰';
echo mb_detect_encoding($text, ['UTF-8', 'CP1252', 'ISO-8859-1'], true);
What I would expect was UTF-8, when the string contains characters outside the Windows/Latin charset - but ...
I have some of the same issues. But find it hard to reason out, why/when the function returns what I want and when it does not.
@mrbase, I will be happy to have a look at these test cases as soon as I find some time and explain exactly what mb_detect_encoding is doing and why.
What I would expect was
UTF-8, when the string contains characters outside the Windows/Latin charset - but ...
Well, that's not quite the way to think about it. You need to think of the string as a sequence of bytes, not characters.
Until we know how a string is encoded, it is not meaningful to talk about "characters". It's just raw bytes. To guess the encoding, we need to look at what those bytes might mean if they were interpreted as UTF-8 text, CP1252 text, or ISO-8859-1 text.
Sure, when interpreted as UTF-8, that string might include characters not in the Latin charset. But that doesn't mean anything. When interpreted as ISO-8859-1, it will most definitely not include characters outside the Latin charset.
@mrbase Just one more point... if you want to provide more information about what you are actually doing, I may (or may not) be able to suggest a better way to achieve your goal.
If your interest is just in mb_detect_encoding and how it works, then I am happy to restrict my comments to that subject and not offer commentary on whether your application should be using mb_detect_encoding or not (hint: it probably shouldn't).
@alexdowad Yeah, I get it - it is not easy at all.
We have a system that runs on both Windows and Linux, and historically all files have been CP1252 encoded.
On Linux you can (in most cases) run file -i some-file.php to find out what the system thinks the file is encoded as - this does not work on Windows, here we read the file - and used mb_detect_encoding to see if the content needed to be converted in order to save it as UTF-8.
Also we use it to find the encoding on csv/txt/.. import files we do not know the encoding of.
And yes, it would be super to have a better understanding of how it works, but I also think you are right in, that we should not use it as we do.
@mrbase Thanks for sharing more info.
I haven't analyzed your test cases yet, but first, if UTF-8 is the "default" encoding which most of your input files are encoded in, I would like to suggest you first try mb_check_encoding to see if the file is valid UTF-8. If it is, just treat it as UTF-8. (Likewise, if CP1252 is the "default", use mb_check_encoding first to see if it's valid as CP1252. Hmm... I don't remember right now whether all strings are valid as CP1252 or not, though...)
If it's not valid in your 'default' encoding, then using mb_detect_encoding to guess from the other possible encodings would be reasonable.
If you want to make things work as well as possible for your users, you could provide a button which they can click if their file contents look 'corrupted'. (For example, say you guessed that the file was the default CP1252, but it's actually UTF-8.) When they click that button, show them a snippet of text from their file when interpreted as UTF-8, CP1252, ISO-8859-1, or whatever other text encodings you support. Let them click on the one which looks right.
@mrbase If you have any ideas of heuristics which could be used to distinguish between CP1252 and ISO-8859-1, I am very open to adding those.
@alexdowad
In our old test case we have the following comment, don't know if it helps or not:
# The following characters are special characters that has different code points in ISO-8859-1 and Windows-1252
# - that we differentiate correctly between ISO-8859-1 and Windows-1252
Œ
‰
Using mb_check_encoding sesam to do the trick tho.
Just to be clear mb_check_encoding is more strict than mb_detect_encoding because it "knows" what char ranges to validate against, correct?
OK, I'll add your test case to the official test cases for the PHP interpreter.
Using
mb_check_encodingsesam to do the trick tho. Just to be clearmb_check_encodingis more strict thanmb_detect_encodingbecause it "knows" what char ranges to validate against, correct?
mb_detect_encoding has 'strict' and 'non-strict' modes. In its 'strict' mode, it rejects any candidate encoding if the input string is invalid in that encoding, which is exactly when mb_check_encoding returns false.
I am suggesting that you use mb_check_encoding not because it is more strict; the point is to give your "default" encoding first chance to be picked. If the input is valid in your "default" encoding, then you can just use that instead of guessing from a list of several candidates.
@alexdowad
Fantastic, will have to restructure some of our code, but with the pointers I guess we are close :) Thanks a bunch!