Rory Rory - 2 years ago 187
PHP Question

What's the difference between escapeshellarg and escapeshellcmd?

PHP has 2 closely related functions,

. They both seem to do similar things, namely help make a string safer to use in

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

Answer Source


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download