In this seventh part of an eight-part article series on using PHP commands with your file and operating systems, you'll learn how and why to sanitize user input. This article is excerpted from chapter 10 of the book Beginning PHP and PostgreSQL 8: From Novice to Professional, written by W. Jason Gilmore and Robert H. Treat (Apress; ISBN: 1590595475).
The escapeshellarg() function delimits arguments with single quotes and prefixes (escapes) quotes found within arguments. The effect is that when arguments is passed to a shell command, it will be considered a single argument. This is significant because it lessens the possibility that an attacker could masquerade additional commands as shell command arguments. Therefore, in the aforementioned nightmarish scenario, the entire user input would be enclosed in single quotes, like so:
'http://www.wjgilmore.com/ ; cd /usr/local/apache/htdoc/; rm -rf *'
The result would be that HTMLDOC would simply return an error, because it could not resolve a URL possessing this syntax, rather than delete an entire directory tree.
escapeshellcmd()
string escapeshellcmd (string command)
The escapeshellcmd() function operates under the same premise as escapeshellarg(), sanitizing potentially dangerous input by escaping shell metacharacters. These characters include the following: # & ; ` , | * ? , ~ < > ^ ( ) [ ] { } $ \\.