What potential security risks are associated with using user input directly in functions like unlink() in PHP scripts?

Using user input directly in functions like unlink() in PHP scripts can lead to security risks such as directory traversal attacks, where an attacker could manipulate the input to delete files outside of the intended directory. To prevent this, it is important to validate and sanitize user input before using it in such functions.

// Validate and sanitize user input before using it in unlink()
$fileToDelete = $_POST['fileToDelete'];

// Check if the file path is within a specific directory
$baseDirectory = '/path/to/your/directory/';
$fullPath = realpath($baseDirectory . $fileToDelete);

if (strpos($fullPath, $baseDirectory) === 0) {
    // File path is within the specified directory, safe to delete
    unlink($fullPath);
} else {
    // File path is outside the specified directory, do not delete
    echo "Invalid file path";
}