What are the potential pitfalls of using variables in shell_exec commands?

Potential pitfalls of using variables in shell_exec commands include security vulnerabilities such as command injection if the variables are not properly sanitized. To mitigate this risk, it is important to always sanitize user input and validate the variables being passed to shell_exec to prevent unauthorized commands from being executed.

// Example of using escapeshellarg to sanitize variables before passing them to shell_exec
$filename = 'example.txt';
$escaped_filename = escapeshellarg($filename);
$output = shell_exec("cat " . $escaped_filename);
echo $output;