How can one ensure that PHP code obtained from external sources is clean and error-free before running it?

When obtaining PHP code from external sources, it is important to ensure that the code is clean and error-free to prevent security vulnerabilities or unexpected behavior. One way to do this is by using a code linter or validator tool to check for syntax errors, coding standards compliance, and potential security issues before running the code.

// Example code snippet using PHP linter to check external code before running it
$externalCode = "echo 'Hello, World!';";
$lintOutput = shell_exec("php -l <<< $externalCode");

if (strpos($lintOutput, 'No syntax errors detected') !== false) {
    // External code is clean and error-free, proceed to run it
    eval($externalCode);
} else {
    // External code contains errors, handle accordingly
    echo "External code contains errors: $lintOutput";
}