What are the potential security risks of using chmod in PHP to change file permissions?

When using chmod in PHP to change file permissions, there is a potential security risk if the input is not properly validated. This can lead to vulnerabilities such as allowing unauthorized users to modify sensitive files or execute malicious code. To mitigate this risk, always sanitize and validate user input before using it in the chmod function.

$filename = 'example.txt';

// Validate user input
if (preg_match('/^[a-zA-Z0-9_]+\.[a-zA-Z]{3}$/', $filename)) {
    // Set file permissions securely
    chmod($filename, 0644);
} else {
    echo "Invalid filename!";
}