Rory Rory - 6 months ago 56
PHP Question

What's the difference between escapeshellarg and escapeshellcmd?

PHP has 2 closely related functions,

and
escapeshellcmd()
. They both seem to do similar things, namely help make a string safer to use in
system()
/
exec()
/etc.

Which one should I use? I just want to be able to take some user input and run a command on it, and not have everything blow up. If PHP had an exec-type-function that took an array of strings (like argv), which bypasses the shell, I'd use that. Similar to Python's
subprocess.call()
function.

Answer

From http://ie2.php.net/manual/en/function.escapeshellarg.php

escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument.

escapeshellarg, as its name indicates, is used as passing shell argument(s). For example, you want to list current directory,

$dir = ".";
system('ls '.escapeshellarg($dir));
escapeshellcmd('ls $dir');

Both do similar things and simply depends on how you handle your logic, do make sure your normalize and validate your input before passing directly to these methods for better security.