What are the potential risks of using dynamic file paths in PHP, especially when dealing with special characters like $?

Using dynamic file paths in PHP can pose a security risk, especially when dealing with special characters like $. This can potentially lead to code injection attacks or unintended file access. To mitigate this risk, it's important to sanitize and validate user input before using it in file paths.

// Example of sanitizing user input for file paths
$userInput = $_GET['file'];
$cleanedInput = preg_replace('/[^a-zA-Z0-9_\-\.]/', '', $userInput);
$filePath = '/path/to/files/' . $cleanedInput;

// Now $filePath is sanitized and safe to use