Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 9 of 10 · Security Best Practices
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:
$filename = $_GET['file'];
system('cat ' . $filename);

Input: file.txt; rm -rf / executes both commands

Safer:
$filename = escapeshellarg($_GET['file']);
system('cat ' . $filename);
PracticeWhy
Avoid shell functions entirely when possibleUse native PHP functions like file_get_contents() instead
escapeshellarg() / escapeshellcmd()Escapes shell metacharacters if shell exec is unavoidable
Whitelist allowed valuesStrongest 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?