Problems with Windows long filenames with shell_exec and `

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jonrosen
Forum Newbie
Posts: 3
Joined: Thu Jun 30, 2005 4:32 pm

Problems with Windows long filenames with shell_exec and `

Post by jonrosen »

If I pass a long filename with embedded blanks to shell_exec in Windows and it is properly double-quoted, it works:

Code: Select all

$cmd = '"C:\Program Files\My Progams\test.exe" --help'; 
$out = shell_exec($cmd);
echo "<pre>".htmlspecialchars($out)."</pre>";
Output of this mini-test program looks like:

Code: Select all

Usage: test &#1111;options] InputFile

where &lt;options&gt; are
  -h or --help
      Print this help
If I try to pass a long filename to the same program, i.e., so that there are TWO filenames both with double quotes, it chokes:

Code: Select all

$cmd = '"C:\Program Files\My Progams\test.exe" "C:\Documents and Settings\jon\My Documents\file.txt"'; 
$out = shell_exec($cmd);
echo "<pre>".htmlspecialchars($out)."</pre>";
Output is now:

Code: Select all

'C:\Program' is not recognized as an internal or external
command, operable program or batch file.
I assume this message comes from windows, not PHP. Taking out the quotes after the first name and before the second name, i.e., enclosing the whole command in double quotes, makes no difference. I get the same error message.

Interestingly, when I paste this string into a DOS Window that is running CMD, it works just fine.

Can anyone tell me the solution to this problem? It seems to happen also with back-tick (which makes sense since both back-tick and shell_exec are the same). I haven't tried any of the other options like popen yet. Hoping someone has an idea.

BTW, I can make the names into 8.3 names (with the ugly ~n things), but that is AWFUL and hardly intuitive if I want the user to select the file from a directory browser.

Thanks in advance!

Jon Rosen
jonrosen
Forum Newbie
Posts: 3
Joined: Thu Jun 30, 2005 4:32 pm

Post by jonrosen »

I figured it out! When there are double quotes in a CMD string, CMD first removes the outermost set of double quotes BEFORE it starts to process the command. Then it processes it just like it was typed in. So, to make this work, I needed to enclose the entire string (including the doubled quoted set of filenames) inside another double quotes and then it worked perfectly!!!!

Code: Select all

$cmd = '""C:\Program Files\My Progams\test.exe" "C:\Documents and Settings\jon\My Documents\file.txt""'; 
$out = shell_exec($cmd);
echo "<pre>".htmlspecialchars($out)."</pre>";
Post Reply