Search code examples
phpgettext

Non-deterministic gettext behavior in PHP


I am using gettext in PHP and I have very strange problem. When I keep reloading the page, the strings are not translated to English most of the time, but sometimes they are!!!

My code goes like this (it is part of bigger code though):

bindtextdomain ('messages', dirname(__FILE__) . '/lang/nocache'); # https://stackoverflow.com/a/13629035 (nevim jestli je to u me problem, ale pro jistotu
bindtextdomain ('messages', dirname(__FILE__) . '/lang');
textdomain('messages');
bind_textdomain_codeset('messages', 'UTF-8');

$rv = setlocale(LC_MESSAGES, 'en_US.UTF-8');
var_dump($rv); # always returns "en_US.UTF-8"

echo "<br>TEST: " . _("Úvod");
echo "<br>TEST: " . _("Výsledky");
echo "<br>TEST: " . gettext("Úvod");

When I just cut this code snippet to a separate PHP file, the text always gets translated. I don't suspect my bigger code though of producing this non-determinism, since this piece of code inside is compact and not affected by other parts. I suspect that this strange non-determinism only appears under certain conditions, and unfortunatelly these conditions go off when I put it in a small test file (you must know this Murphy law nightmare very well :-)).

I don't know if it is a gettext cache problem, but I haven't changed the translations. I tried the recommended nocache dir trick and I also tried to restart Apache (Apache/2.4.10 (Debian)), but it didn't help. My PHP version is 5.6.12-0+deb8u1.

How can this be non-deterministic? Where is the problem?


EDIT: encoding in /etc/php5/apache2/php.ini:

; PHP's default character set is set to UTF-8.
; http://php.net/default-charset
default_charset = "UTF-8"

; PHP internal character encoding is set to empty.
; If empty, default_charset is used.
; http://php.net/internal-encoding
;internal_encoding =

; PHP input character encoding is set to empty.
; If empty, default_charset is used.
; http://php.net/input-encoding
;input_encoding =

; PHP output character encoding is set to empty.
; If empty, default_charset is used.
; mbstring or iconv output handler is used.
; See also output_buffer.
; http://php.net/output-encoding
;output_encoding =

Solution

  • There was indeed a problem in the directory, because the code with __FILE__ was in different directory and I included it and didn't realize that the __FILE__ will then give wrong path. So I hardcoded the path instead:

    bindtextdomain('messages', './lang/nocache'); # http://stackoverflow.com/a/13629035 
    bindtextdomain('messages', './lang');
    

    But what is really strange is that even with the wrong directory, it sometimes worked!!! This is really treacherous.