Can't get gettext (php) on Ubuntu working
When a translation setup that functions perfectly on macOS Apache suddenly breaks on Ubuntu with lighttpd, it usually points to a misalignment between how the application sets its locale and how the web server processes those environment variables. The core issue in this scenario is not file permissions or missing .mo filesâsince file_get_contents() successfully retrieves the binary dataâbut rather the timing and scope of locale initialization relative to the PHP process lifecycle.
The provided code snippet attempts to force a specific locale by setting both putenv() variables and calling setlocale(). While this often works on macOS, it is fragile in production environments, particularly when using lighttpd or other lightweight servers that may isolate environment contexts differently than Apache.
The Timing of Locale Initialization
The most critical failure point in the original code is the placement of setlocale() and bindtextdomain(). These functions must be called before any output is generated. If PHP has already initialized its locale settings using default system values, subsequent calls to setlocale() will either fail silently or have no effect on the current process state depending on the specific PHP version and build flags.
In many cases, developers assume that setting these variables inside a script block is sufficient. However, if the script contains any logic before the translation setupâsuch as database connections that might trigger locale-dependent string operationsâor if the web server pre-initializes certain contexts, the explicit calls may be ignored. The order of operations is paramount:
- Set
LC_*environment variables viaputenv(). - Call
setlocale(LC_ALL, $locale). - Call
bindtextdomain()andtextdomain(). - Immediately call the translation function (e.g.,
_("...")).
Any output generated before these steps will remain in the default locale, which is often why developers see "Inactive account" instead of the Swedish equivalent.
Environment Variable Scope with lighttpd
A common pitfall arises when comparing Apache and lighttpd configurations. Apache typically inherits environment variables from the OS user context running the worker processes. Lighttpd, by contrast, can be configured to spawn child processes in isolated environments or may strip certain environment variables upon startup depending on the server.document-root and security settings.
If you are using a system service manager like systemd to run lighttpd, the environment might not propagate the LANG or LC_ALL variables set globally by the user session. The solution is often to ensure these variables are explicitly passed to the PHP-FPM or CGI process that lighttpd invokes. This can be achieved by editing the lighttpd configuration file (e.g., /etc/lighttpd/lighttpd.conf) and adding an env directive:
server.document-root = "/var/www/html"
$HTTP["url"] =~ "^/.*" => (
"env.LANG" => "sv_SE.UTF-8",
"env.LC_ALL" => "sv_SE.UTF-8"
);
This forces the environment variables to be present for every request, bypassing any inconsistencies in how lighttpd handles inherited environment data.
Why putenv Alone Is Insufficient
The code snippet includes multiple attempts to set locale: putenv("LANG=$locale"), putenv("LANGUAGE=$locale"), and setlocale(LC_ALL, $locale). While putenv() is useful for modifying the environment visible to child processes spawned by PHP (like exec or popen), it does not retroactively change the current process's internal locale state if setlocale() hasn't already been called successfully.
Furthermore, bindtextdomain() requires the domain name ('flattr' in this case) to match exactly what is specified when compiling or installing the .mo file using msgfmt. If the domain name mismatchesâeven by a single characterâgettext will fail to locate the translation files. Ensure that the path passed to bindtextdomain('flattr', $dir) correctly points to the directory containing the sv_SE/LC_MESSAGES/flattr.mo file, and that the directory structure matches the expected gettext hierarchy:
$dir/
âââ sv_SE/
âââ LC_MESSAGES/
âââ flattr.mo
A Robust Pattern for Production
To avoid these pitfalls, adopt a pattern where locale initialization happens as early as possible, ideally at the very top of every script or within a dedicated bootstrap file included universally. Avoid relying on putenv() for the current process's behavior; rely on setlocale(). Additionally, consider using textdomain('flattr', $dir) (available in PHP 5.4+) to explicitly specify the directory path alongside the domain name, which can prevent lookup failures if the default search paths are restricted.
<?php
// Set at the very beginning of every script
$locale = 'sv_SE.UTF-8'; // Prefer UTF-8 for modern systems
putenv("LANG=$locale");
putenv("LC_ALL=$locale");
putenv("LC_MESSAGES=$locale");
// Must happen before any output
if (!setlocale(LC_ALL, $locale)) {
throw new RuntimeException("Locale $locale not supported or failed to set.");
}
bindtextdomain('flattr', dirname(__FILE__));
textdomain('flattr');
echo _("Inactive account");
By strictly adhering to this initialization order and ensuring the web server explicitly provides the necessary environment variables, you can achieve consistent translation behavior across different operating systems and web servers.