Amandasaurus
Amandasaurus

Reputation: 60799

Execute an external command by passing an array, with spaces in filenames

I have a PHP script that needs to execute programmes that will work on files that have spaces in the names. Most PHP functions for executing external commands (e.g. exec()) take an 1 string argument for the command line to execute. However then you have to do things like escapeshellarg() to make your input safe.

Is there some way to execute an external command in PHP with an array. So rather than:

exec("ls -l ".escapeshellarg($filename));

I can go:

exec(array("ls", "-l", $filename));

This would mean I don't have to worry about escaping the arguments. I want to avoid using escapeshellarg(), since the version I am using has a bug that strips out non-ASCII characters.

Java has this functionality http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec%28java.lang.String[]%29

Upvotes: 2

Views: 2061

Answers (3)

Amandasaurus
Amandasaurus

Reputation: 60799

Sounds like this isn't possible with PHP's builtin functions.

Upvotes: 2

mr-sk
mr-sk

Reputation: 13417

Poke's answer is good - however, how many commands do they need to run? I would think about implementing a whitelist of commands and arguments - that way, you can be pretty darn sure they aren't injection malicious input. Something like:

$whitelistCommandArray = array('ls' => 'ls', ...);
if (isset($whitelistCommandArray[$userSuppliedCommand]])
{
    //ok its a valid command, lets parse the args next
    ...
}
else echo "Unsupported command";

Update/edit:

Is a whitelist of arguments feasible? What if OP needs to edit a multitude of files? – Matchu

heh I dont know - it could be - totally depends on your needs.

$whitelistArray = array('ls' => array('a', 'l', 'h'), ...);

Something like that work - with both the command and then an array of arguments for it.

Upvotes: -1

poke
poke

Reputation: 388313

function myExec ( command, arguments )
{
    exec( command + ' ' + implode( ' ', array_map( escapeshellarg, arguments ) ) );
}

Upvotes: 1

Related Questions