Escapes shell metacharacters in a command string.
What Is escapeshellcmd() in PHP?
Escapes shell metacharacters in a command string.
Its syntax is:
escapeshellcmd(string $command): string
Parameters:
$command— Accepted as string; required argument.
Return type: string. This does not protect individual arguments and is not a substitute for escapeshellarg() or command allowlisting. Prefer no shell invocation.
Availability: Escaping varies by platform and configured shell.
Example 1: Basic Usage
<?php
echo escapeshellcmd("echo report; whoami");
Output:
echo report\; whoami
This does not protect individual arguments and is not a substitute for escapeshellarg() or command allowlisting. Prefer no shell invocation.
Example 2: A Different Input
<?php
echo escapeshellcmd("tool --help");
Output:
tool --help
This does not protect individual arguments and is not a substitute for escapeshellarg() or command allowlisting. Prefer no shell invocation.
Practical Example: Applying It in a Program
<?php
$staticCommand = "echo status"; echo escapeshellcmd($staticCommand);
Output:
echo status
This does not protect individual arguments and is not a substitute for escapeshellarg() or command allowlisting. Prefer no shell invocation.
Important Behavior and Edge Cases
- Key behavior: This does not protect individual arguments and is not a substitute for escapeshellarg() or command allowlisting. Prefer no shell invocation.
- Environment: Escaping varies by platform and configured shell.
Comparison With Related Functions
| Function | Purpose |
|---|---|
escapeshellcmd() | Escapes shell metacharacters in a command string. |
escapeshellarg() | escapeshellarg() quotes one argument; escapeshellcmd() does not safely separate untrusted arguments. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: This does not protect individual arguments and is not a substitute for escapeshellarg() or command allowlisting | This does not protect individual arguments and is not a substitute for escapeshellarg() or command allowlisting. Prefer no shell invocation. |
Key Takeaways
- Escapes shell metacharacters in a command string.
- This does not protect individual arguments and is not a substitute for escapeshellarg() or command allowlisting. Prefer no shell invocation.
- Escaping varies by platform and configured shell.
Summary: This does not protect individual arguments and is not a substitute for escapeshellarg() or command allowlisting. Prefer no shell invocation.