What are some best practices for securely using the eval() function in PHP to prevent parse errors?

When using the eval() function in PHP, it is important to securely handle the input to prevent parse errors and potential security vulnerabilities. One way to do this is by using proper error handling and validation techniques to ensure that the input being evaluated is safe and properly formatted.

// Example of securely using the eval() function in PHP
$input = "echo 'Hello, world!';";

// Check if the input is a valid PHP code
if (is_string($input) && trim($input) !== '') {
    // Use eval() only if the input is safe
    eval($input);
} else {
    // Handle invalid input
    echo "Invalid input";
}