How do I to properly handle spaces in PHP Shell_exec?

狂风中的少年 提交于 2019-12-05 14:12:33

Use escapeshellarg() to escape your arguments, it should escape it with an appropriate combination of quotation marks and escaped spaces for your platform (I'm guessing you're on Windows).

Unlike Unix, which requires quotes within quotes to be escaped, Windows doesn't seem to work this way. 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" "';
$fp = popen($cmd, 'r');
$output='';
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. Without these outside quotes, DOS does some weird things. 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!

This is an interesting problem. Apparently, PHP lets you put double quotes around the program or the arguments, but not both. It may be worth reporting this as a bug.

A work around is to use the DOS 8.3 name instead of quotes. E.g., "C:\Program Files\" usually becomes "C:\Progra~1".

Had this problem too - came up with an idea to route the launching through cmd.exe. The trick here is not to get lost in the double 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. Example:

$path = '"C:\Program Files\ToDoList Simple\ToDoList.exe" "C:\SomePath\todo.tdl" -nt test -cm test2';
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!