The PHP Filter module has been removed from Drupal core because improperly using it would cause security issues. The security issues were mitigated from the fact that only users with the use PHP for settings permission could use the input filter, but that doesn't sanitize the code entered by editors. If then the permission were unconditionally given to every editor, it's like that permission didn't exist.
The Drupal core module is now available as PHP module, but I would not use it.
I would rather do what Hudri suggested, and use the Token Filter module. With that module, and adding its input filter to the input format used for nodes, a user could enter a token which would be replaced with its value. Instead of PHP snippets, I would implement custom tokens that are replaced by the value returned from the PHP code executed in hook_tokens()
, one of the hooks necessary to modules that want to implement custom tokens.
function mymodule_token_info() {
$type = [
'name' => t('Custom tokens'),
'description' => t('Custom tokens to use in the node body field.'),
];
// Custom global tokens.
$custom['custom01'] = [
'name' => t("Custom 01"),
];
$custom['custom02'] = [
'name' => t("Custom 02"),
];
return [
'types' => [
'custom' => $type,
],
'tokens' => [
'custom' => $custom,
],
];
}
function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$replacements = [];
if ($type == 'custom') {
foreach ($tokens as $name => $original) {
if ($name == 'custom01') {
$replacements[$original] = // Set the value of the custom01 token.
}
elseif ($name == 'custom02') {
$replacements[$original] = // Set the value of the custom02 token.
}
}
}
return $replacements;
}
hook_tokens()
could also return HTML markup used for the node body field. $bubbleable_metadata
can be used to add cache dependencies.
This method is safer, as it doesn't allow users to enter arbitrary PHP code which, potentially, could also change the password for any user account, delete all the site content, or send users information to external sites.
Even if only trusted users were allowed to use the PHP input filter, there are always chances the entered code causes issues.