18.20. Escaping Shell Metacharacters
Problem
You need to incorporate external data in a command line, but you want to escape out special characters so nothing unexpected happens; for example, you want to pass user input as an argument to a program.
Solution
Use escapeshellarg( )
to handle arguments:
system('ls -al '.escapeshellarg($directory));Use escapeshellcmd( ) to handle program names:
system(escapeshellcmd($ls_program).' -al');
Discussion
The command line is a dangerous place for unescaped characters. Never pass unmodified user input to one of PHP’s shell-execution functions. Always escape the appropriate characters in the command and the arguments. This is crucial. It is unusual to execute command lines that are coming from web forms and not something we recommend lightly. However, sometimes you need to run an external program, so escaping commands and arguments is useful.
escapeshellarg( ) surrounds arguments with
single quotes (and
escapes any existing single quotes). To print the process status for
a particular process:
system('/bin/ps '.escapeshellarg($process_id));Using escapeshellarg( ) ensures that the right
process is displayed even if it has an unexpected character (e.g., a
space) in it. It also prevents unintended commands from being run. If
$process_id contains:
1; rm -rf /
then:
system("/bin/ps $process_id")not only displays the status of process 1, but it also executes the command rm -rf / . However:
system('/bin/ps '.escapeshellarg($process_id))runs the command ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access