PHP。从命令行和浏览器

时间:2018-05-07 15:14:35

标签: php browser encoding utf-8

我有这个PHP脚本:

<?php
  $cmd_desformat = "/usr/local/bin/process /tmp/input.txt > /tmp/output.txt";
  shell_exec($cmd_desformat);

其中input.txt是UTF-8文件(使用&#34;文件-i&#34;检查),其中包含:

Buenos días

和/ usr / local / bin / process是来自第三方的二进制可执行文件,我已经广泛使用并且从未遇到过这个问题。

嗯,问题是当我从浏览器执行此操作时:

http://localhost/test.php

结果output.txt是一个US-ASCII文件,包含:

Buenos d?as [][

但是,当我从命令行执行此操作时:

php test.php

结果output.txt是一个带有预期的UTF-8文件:

Buenos días [][

我尝试从用户www-data的命令行执行,看看我是否可以复制浏览器行为,但结果又是正确的。我还尝试使用exec代替shell_exec,但结果是一样的。还尝试使用Firefox和Chrome。

从浏览器调用时我需要它才能工作。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

PHP CLI环境与shell_exec环境不同。如何设法让您的内容以正确的方式返回,有两种可能性。

最简单的方法是在env -i来电中调用shell_exec来重置环境。

<?php
  $cmd_desformat = "env -i /usr/local/bin/process /tmp/input.txt > /tmp/output.txt";
  shell_exec($cmd_desformat);

如果未正确设置默认环境,则此功能可能无效。如果是这种情况,那么您可能需要使用putenv()显式设置它。

<?php
  putenv('LANG=en_US.UTF-8'); // Set this to the language you need
  $cmd_desformat = "/usr/local/bin/process /tmp/input.txt > /tmp/output.txt";
  shell_exec($cmd_desformat);