Check if a Function Exists
Checks whether a PHP function exists, restricts callable execution to an allowlist, and optionally runs the approved function.
Purpose
Checks whether a PHP function exists, restricts callable execution to an allowlist, and optionally runs the approved function.
Snippet details
ContextUtilityLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Check if a Function Exists.
*
* Purpose:
* Uses function_exists() to inspect availability and demonstrates an allowlist
* before calling a function dynamically.
*
* @param string $function_name Function name to inspect.
* @param array $arguments Optional arguments for approved callable execution.
* @return array Function availability and optional result.
*/
function ogSnippetCheckIfFunctionExists(string $function_name, array $arguments = array()): array {
$function_name = trim($function_name);
if ($function_name === '') {
return array(
'exists' => false,
'executed' => false,
'result' => null,
'message' => 'Function name is required.'
);
}
$exists = function_exists($function_name);
$allowed_to_execute = array('trim', 'strtolower', 'strtoupper', 'strlen');
if ($exists === false) {
return array(
'exists' => false,
'executed' => false,
'result' => null,
'message' => 'Function does not exist.'
);
}
if (in_array($function_name, $allowed_to_execute, true) === false) {
return array(
'exists' => true,
'executed' => false,
'result' => null,
'message' => 'Function exists but is not approved for dynamic execution.'
);
}
$result = call_user_func_array($function_name, $arguments);
return array(
'exists' => true,
'executed' => true,
'result' => $result,
'message' => 'Approved function executed.'
);
}
/*
$result = ogSnippetCheckIfFunctionExists('strtolower', array('SERENITY CARGO HOLD'));
print_r($result);
*/