Escapes one string for use as a single shell command argument.
What Is escapeshellarg() in PHP?
Escapes one string for use as a single shell command argument.
Its syntax is:
escapeshellarg(string $arg): string
Parameters:
$arg— Accepted as string; required argument.
Return type: string. Escaping arguments does not validate command choice. Avoid a shell where a native API exists; do not execute untrusted commands.
Availability: Shell quoting is platform-dependent, especially on Windows.
Example 1: Basic Usage
<?php
echo escapeshellarg("file name.txt");
Output:
'file name.txt'
Escaping arguments does not validate command choice. Avoid a shell where a native API exists; do not execute untrusted commands.
Example 2: A Different Input
<?php
echo escapeshellarg("name; echo unsafe");
Output:
'name; echo unsafe'
Escaping arguments does not validate command choice. Avoid a shell where a native API exists; do not execute untrusted commands.
Practical Example: Applying It in a Program
<?php
$filename = "annual report.csv"; $safeArgument = escapeshellarg($filename); echo "Argument: " . $safeArgument;
Output:
Argument: 'annual report.csv'
Escaping arguments does not validate command choice. Avoid a shell where a native API exists; do not execute untrusted commands.
Important Behavior and Edge Cases
- Key behavior: Escaping arguments does not validate command choice. Avoid a shell where a native API exists; do not execute untrusted commands.
- Environment: Shell quoting is platform-dependent, especially on Windows.
Comparison With Related Functions
| Function | Purpose |
|---|---|
escapeshellarg() | Escapes one string for use as a single shell command argument. |
escapeshellcmd() | escapeshellcmd() quotes shell metacharacters in a whole command; escapeshellarg() treats a value as a single shell argument. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: Escaping arguments does not validate command choice | Escaping arguments does not validate command choice. Avoid a shell where a native API exists; do not execute untrusted commands. |
Key Takeaways
- Escapes one string for use as a single shell command argument.
- Escaping arguments does not validate command choice. Avoid a shell where a native API exists; do not execute untrusted commands.
- Shell quoting is platform-dependent, especially on Windows.
Summary: Escaping arguments does not validate command choice. Avoid a shell where a native API exists; do not execute untrusted commands.