What are some best practices for safely displaying and editing PHP code stored in a database within a web application?

When displaying and editing PHP code stored in a database within a web application, it is crucial to prevent potential security risks such as code injection attacks. One best practice is to properly sanitize and escape the code before displaying it to prevent malicious code execution. Additionally, limit the permissions of users who can edit the code and implement proper input validation to ensure only safe and expected code is stored in the database.

// Sanitize and escape PHP code before displaying it
$stored_php_code = htmlspecialchars($stored_php_code);

// Limit user permissions for editing PHP code
if($user_role === 'admin'){
    // Allow editing
} else {
    // Display read-only view
}

// Input validation before storing PHP code in the database
$php_code_to_store = $_POST['php_code_to_store'];
if(preg_match('/^[a-zA-Z0-9_ ;{}()$]*$/', $php_code_to_store)){
    // Store the code in the database
} else {
    // Display an error message
}