Interview question
What is command injection and how do you prevent it in PHP? Command injection क्या है और PHP में इसे कैसे रोकें?
Answer
Command injection happens when user input is passed unsanitized into shell execution functions, letting attackers run arbitrary system commands.
Vulnerable:
Input:
Safer:
$filename = $_GET['file'];
system('cat ' . $filename);Input:
file.txt; rm -rf / executes both commandsSafer:
$filename = escapeshellarg($_GET['file']);
system('cat ' . $filename);| Practice | Why |
|---|---|
| Avoid shell functions entirely when possible | Use native PHP functions like file_get_contents() instead |
| escapeshellarg() / escapeshellcmd() | Escapes shell metacharacters if shell exec is unavoidable |
| Whitelist allowed values | Strongest defense - only permit known-safe inputs |
Command injection तब होता है जब user input बिना sanitize किए shell execution functions में जाता है।
असुरक्षित:
सुरक्षित:
$filename = $_GET['file'];
system('cat ' . $filename);सुरक्षित:
$filename = escapeshellarg($_GET['file']);
system('cat ' . $filename);Was this answer clear?