如何在 php 中执行的 shell 命令中处理 unicode 字符 (utf8)

How to process unicode characters (utf8) in shell command executed in php

我有 dir 函数,我用它来查找所有可执行文件和目录,它有这样的代码:

    $EXEC = 'X';
    $DIR = 'D';
    $FILE = 'F';
    // depend on GNU version of find (not tested on different versions)
    $cmd = "find . -mindepth 1 -maxdepth 1 \( -type f -executable -printf ".
           "'$EXEC%p\0' \)  -o -type d -printf '$DIR%p\0' -o \( -type l -x".
           "type d -printf '$DIR%p\0' \) -o -not -type d -printf '$FILE%p\0'";
    $result = $this->command($token, $cmd, $path);

我的命令函数有这样的代码:

    $pre .= ";export LC_ALL=en_US.UTF-8; export HOME='$home';cd '$path'; $aliases\n";
    $post = ";echo -n \"$marker\";pwd";
    $command = escapeshellarg($pre . $command . $post);
    $command = $this->sudo($token, $username, '/bin/bash -c ' . $command . ' 2>&1');
    $command = $this->unbuffer($token, $command);
    $result = $this->$shell_fn($token, $command);

其中 $shell_fn 是 shell exec 函数之一或 perl/python 使用 curl 的 cgi 调用。

通过在命令前添加 export LC_ALL=en_US.UTF-8 我已经解决了 ls 的问题,它现在显示具有像 Robert Gawliński 这样的 unicode 字符的内容,但是当我这样做时 echo ą 或尝试在它中断的目录 Robert Gawliński 上调用 dir。 echo ą 显示 Ä 并且 cd Robert Gawliński 显示错误

/bin/bash: line 2: cd: $'Robert GawliÅ24ski/': No such file or directory

似乎 shell 命令的输入是由 php 语言环境处理的,所以:

  1. 要处理输出,您需要在 exec
  2. 中导出 LC_ALL
  3. 但要输入您需要调用:
$locale = 'en_US.UTF-8';
setlocale(LC_ALL, $locale);
putenv('LC_ALL='.$locale);