简体   繁体   中英

php exec() with arguments containing spaces

I want to use PHP to run a shell command that takes a directory as an argument. The problem is, this directory name contains both single quotes and spaces. In shell, if the directory is called "I'm a directory", this would be something like:
ls I\\'m\\ a \\ directory

However, I am not able to get this working when invoking through PHP. I tried
exec('ls I\\'m\\ a\\ directory')
and many other variations, but none of them seem to work. Any suggestions? Thanks in advance!

There is php function escapeshellarg for this. You enter whatever string you need and result is string formated so you can use it as one argument in shell:

$rawArgument = "I'm a directory";
$escapedArgumment = escapeshellarg($rawArgument);
exec("ls $escapedArgumment");

You'll need to double escape your slashes correctly to ensure they don't get eaten by the string.

Part of your problem is that \\' is being eaten and passed to the command line as just ' .

Compare these:

echo 'ls I\'m\ a\ directory';
echo "\n";
echo "ls I\'m\ a\ directory"; //Note double quotes
echo "\n";
echo 'ls I\\\'m\\ a\\ directory';
echo "\n";
echo "ls I\\\'m\\ a\\ directory";  //Note double quotes

Results in:

ls I'm\ a\ directory
ls I\'m\ a\ directory
ls I\'m\ a\ directory
ls I\\'m\ a\ directory

So what you really want is either of these:

exec('ls I\\\'m\ a\ directory')
exec("ls I\'m\ a\ directory")

Try this:

passthru('ls "I\'m a directory"');

exec() returns the last line of output, which might not be what you expected. Compare it to this:

exec('ls "I\'m a directory"', $outvar);
print_r($outvar);

I assume all have read the fine manual, but here it is, just in case: http://us1.php.net/manual/en/function.exec.php

Example proof-of-concept session on FreeBSD:

501:~$ mkdir "I'm a directory"
502:~$ ls -lrt
drwxr-xr-x   2 cxj  cxj       512 Jul  2 19:32 I'm a directory
drwxr-xr-x  33 cxj  cxj      2048 Jul  2 19:32 .
503:~$ cd I\'m\ a\ directory/
504:~/I'm a directory$ touch foo bar baz
505:~/I'm a directory$ cd ..
506:~$ cat - > test.php
<?php passthru('ls "I\'m a directory"'); ?>
507:~$ cat test.php
<?php passthru('ls "I\'m a directory"'); ?>
508:~$ php test.php
bar
baz
foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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