Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

Shell Commands

Be very wary of using the exec( ) , system( ), passthru( ), and popen( ) functions and the backtick (`` ) operator in your code. The shell is a problem because it recognizes special characters (e.g., semicolons to separate commands). For example, suppose your script contains this line:

system("ls $directory");

If the user passes the value "/tmp;cat /etc/passwd" as the $directory parameter, your password file is displayed because system( ) executes the following command:

ls /tmp;cat /etc/passwd

In cases where you must pass user-supplied arguments to a shell command, use escapeshellarg( ) on the string to escape any sequences that have special meaning to shells:

$cleaned_up = escapeshellarg($directory);
system("ls $cleaned_up");

Now, if the user passes "/tmp;cat /etc/passwd", the command that’s actually run is:

ls '/tmp;cat /etc/passwd'

The easiest way to avoid the shell is to do the work of whatever program you’re trying to call. Built-in functions are likely to be more secure than anything involving the shell.

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.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Programming PHP, 2nd Edition

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata