views:

241

answers:

3

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

+2  A: 
function myExec ( command, arguments )
{
    exec( command + ' ' + implode( ' ', array_map( escapeshellarg, arguments ) ) );
}
poke
Good suggestion, but I want to avoid using escapeshellarg() (I've updated the question accordingly). The version I'm using has a bug that strips out non-ASCII characters.
Rory
Feel free to replace that function by any other function (define one yourself for example) that filters the characters correctly. I just wanted to give you an idea how to do it :)
poke
Why the downvote btw?
poke
A: 

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.

Mr-sk
Is a whitelist of arguments feasible? What if OP needs to edit a multitude of files?
Matchu
Yes I do need this script to run on thousands of files that could be named anything and almost certainly will have spaces in their names.
Rory
A: 

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

Rory