Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top