Freddo411
Freddo411

Reputation: 2343

How do I to properly handle spaces in PHP Shell_exec?

I'm running on win2003 server, PHP 526, via the cmd-line.

I have a cmdline string:

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

Trying to do this in php code

$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".

However, the same $cdm string copied to the windows shell cmdline executes successfully.

How do I properly handle spaces in PHP shell_exec?

Upvotes: 4

Views: 7242

Answers (4)

Ben
Ben

Reputation: 11

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!

Upvotes: 1

user187383
user187383

Reputation: 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';

Upvotes: 0

nate
nate

Reputation:

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".

Upvotes: 0

Ciaran McNulty
Ciaran McNulty

Reputation: 18868

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).

Upvotes: 6

Related Questions