[ACCEPTED]-PHP exec() and spaces in paths-exec

Accepted answer
Score: 12

I don't believe addslashes() does anything with spaces. escapeshellarg() might 1 be what you want instead. Docs on escapeshellarg

Score: 10

From the PHP doc (here),

Returns a string with 7 backslashes before characters that need 6 to be quoted in database queries etc. These 5 characters are single quote ('), double 4 quote ("), backslash () and NUL (the 3 NULL byte).

This won't do anything to the 2 spaces. What you will need to do is use 1 str_replace() to add slashes, like this:

$new_string = str_replace(" ", "\\ ", $old_string);

Score: 7

According to the PHP docs,

Returns a string with 11 backslashes before characters that need 10 to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).

Looks 9 like you'll have to preg_replace the spaces 8 yourself.

Edit:

Even though this is the topic of 7 another discussion, if performance is an 6 issue, then after looking into it a little 5 more, it seems that str_replace is actually quite a bit 4 faster than preg_replace:

The test labeled "str_replace()" was the 3 faster by 0.9053 seconds (it took 10.3% the 2 time.)

The first test took 1.0093 seconds. (preg_replace)

The 1 second test took 0.104 seconds. (str_replace)

Benchmark found here.

Score: 5

I've used exec() with paths with spaces before, on 5 both Windows and Linux hosts, and in both 4 cases quoting the path worked perfectly 3 for me.

That said, if you have no control 2 over the safety of a shell argument, always run 1 it through escapeshellarg() first!

Score: 3

You can very well use shell quotes, since that 3 is what all exec commands run through:

exec("php bin/createjob.php '$source' '$output_dir'", $output);

It 2 btw works not just for arguments, but also 1 for the command itself:

exec('"/bin/echo" "one parameter"');

Use escapeshellcmd() anyway.

Score: 0

this works for me when using exec() with 1 soffice(LibreOffice):

$file_name = "Some, file name.xlsx";
exec('/usr/bin/soffice --headless --convert-to pdf '."'".$file_name."'".' 2>&1', $output, $r);

More Related questions