Search code examples
phpshell

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!


Solution

  • 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: https://www.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