How can the use of eval() in PHP be dangerous and what are the alternatives?

Using eval() in PHP can be dangerous because it allows for the execution of arbitrary code, opening up the possibility of code injection attacks. A safer alternative is to use functions like call_user_func() or create_function() to achieve similar functionality without the security risks associated with eval().

// Using call_user_func() as an alternative to eval()

$function_name = 'my_function';
$arg1 = 'argument1';
$arg2 = 'argument2';

if(function_exists($function_name)) {
    call_user_func($function_name, $arg1, $arg2);
} else {
    echo 'Function does not exist.';
}