简体   繁体   English

如何在PHP Shell_exec中正确处理空格?

[英]How do I to properly handle spaces in PHP Shell_exec?

I'm running on win2003 server, PHP 526, via the cmd-line. 我通过cmd-line运行win2003服务器,PHP 526。

I have a cmdline string: 我有一个cmdline字符串:

$cmd = '  "d:\Prog Files\foo.exe" -p "d:\data path\datadir"  ';  

Trying to do this in php code 试图在PHP代码中执行此操作

$out = `$cmd`;       # note use of backticks AKA shell_exec

results in a failure by foo.exe as it interprets the -p arg as "d:\\data". foo.exe导致失败,因为它将-p arg解释为“d:\\ data”。

However, the same $cdm string copied to the windows shell cmdline executes successfully. 但是,复制到windows shell cmdline的相同$cdm字符串会成功执行。

How do I properly handle spaces in PHP shell_exec ? 如何在PHP shell_exec正确处理空格?

使用escapeshellarg()来转义你的参数,它应该使用适当的引号和你的平台的转义空格组合来逃避它(我猜你是在Windows上)。

Unlike Unix, which requires quotes within quotes to be escaped, Windows doesn't seem to work this way. 与Unix不同,它需要在引号内引用才能进行转义,Windows似乎不会以这种方式工作。 How it keeps track of the quotes is beyond me, but this actually seems to work, despite all logic to the contrary: 如何跟踪报价是超出我的,但这实际上似乎有效,尽管所有逻辑相反:

$cmd = '" "C:\\Path\\To\\Command" "Arg1" "Arg2" "'; $ cmd ='“”C:\\ Path \\ To \\ Command“”Arg1“”Arg2“”';
$fp = popen($cmd, 'r'); $ fp = popen($ cmd,'r');
$output=''; $输出= '';
while ($l = fgets($fp, 1024)) while($ l = fgets($ fp,1024))
$output.=$l; $输出= $升。

I'm guessing command.exe is taking the command string total and nixing the (otherwise redundant) outside quotes. 我猜测command.exe正在使用命令字符串total并且修改(否则是多余的)外部引号。 Without these outside quotes, DOS does some weird things. 如果没有这些外部引用,DOS会做一些奇怪的事情。 This solution is similar to post by user187383, but does away with the "cmd /c" which only obfuscates what's actually happening along with a mild performance cut, since cmd /c is implicit by the shell call in the first place! 这个解决方案与用户187383类似,但是不使用“cmd / c”,它只会模糊实际发生的事情以及温和的性能削减,因为cmd / c首先是shell调用所隐含的!

This is an interesting problem. 这是一个有趣的问题。 Apparently, PHP lets you put double quotes around the program or the arguments, but not both. 显然,PHP允许你在程序或参数周围加上双引号,但不能同时使用两者。 It may be worth reporting this as a bug. 可能值得将此报告为错误。

A work around is to use the DOS 8.3 name instead of quotes. 解决方法是使用DOS 8.3名称而不是引号。 Eg, "C:\\Program Files\\" usually becomes "C:\\Progra~1". 例如,“C:\\ Program Files \\”通常变为“C:\\ Progra~1”。

Had this problem too - came up with an idea to route the launching through cmd.exe. 有这个问题 - 提出了通过cmd.exe路由启动的想法。 The trick here is not to get lost in the double qoutes. 这里的诀窍是不要迷失在双qoutes中。 Generally you want to put anything you want to run in: 通常,您希望放置要运行的任何内容:

exec('cmd /c " '.$path.' "';

Where $path is a already double-quoted path to your executable. 其中$ path是可执行文件的双引号路径。 Example: 例:

$path = '"C:\Program Files\ToDoList Simple\ToDoList.exe" "C:\SomePath\todo.tdl" -nt test -cm test2';

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

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