How can PHP code stored in a database be executed safely within a script?

When storing PHP code in a database, it can be risky as it opens up the possibility of executing malicious code. To execute PHP code stored in a database safely within a script, you can first retrieve the code from the database and then use the `eval()` function to execute it. However, it is crucial to sanitize and validate the code before executing it to prevent any security vulnerabilities.

// Retrieve PHP code from the database
$stored_code = "echo 'Hello, World!';";

// Sanitize and validate the code
if (/* Add your validation logic here */) {
    // Execute the sanitized code
    eval($stored_code);
} else {
    // Handle invalid code
    echo "Invalid code detected.";
}