繁体   English   中英

PHP。 从命令行和浏览器调用shell_exec时的不同编码

[英]PHP. Different encoding when calling shell_exec from command line and browser

我有这个php脚本:

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

其中input.txt是UTF-8文件(用“ file -i”检查),其中包含:

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。

从浏览器调用时,我需要它工作。 有任何想法吗?

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

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

<?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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM