Php проверить доступность функции

function_exists

Проверяет, есть ли в списке определённых функций, как встроенных, так и пользовательских, функция function_name .

Список параметров

Возвращаемые значения

Возвращает TRUE , если function_name существует и является функцией, иначе возвращается FALSE .

Замечание:

Эта функция возвращает FALSE для языковых конструкций, таких как include_once или echo .

Примеры

Пример #1 Пример использования function_exists()

if ( function_exists ( ‘imap_open’ )) echo «IMAP функции доступны.
\n» ;
> else echo «IMAP функции недоступны.
\n» ;
>
?>

Примечания

Замечание:

Обратите внимание, что название функции может присутствовать, даже если саму функцию невозможно использовать из-за настроек конфигурации или опций компиляции (например, как для функций image).

Смотрите также

  • method_exists() — Проверяет, существует ли метод в данном классе
  • is_callable() — Проверяет, может ли значение переменной быть вызвано в качестве функции
  • get_defined_functions() — Возвращает массив всех определённых функций
  • class_exists() — Проверяет, был ли объявлен класс
  • extension_loaded() — Определение, загружено ли расширение

Источник

function_exists

Проверяет, есть ли в списке определённых функций, как встроенных (внутренних), так и пользовательских, функция function .

Список параметров

Имя функции в виде строки.

Возвращаемые значения

Возвращает true , если function существует и является функцией, иначе возвращается false .

Замечание:

Эта функция возвращает false для языковых конструкций, таких как include_once или echo .

Примеры

Пример #1 Пример использования function_exists()

if ( function_exists ( ‘imap_open’ )) echo «Функции IMAP доступны.
\n» ;
> else echo «Функции IMAP недоступны.
\n» ;
>
?>

Примечания

Замечание:

Обратите внимание, что название функции может присутствовать, даже если саму функцию невозможно использовать из-за настроек конфигурации или опций компиляции (например, как для функций image).

Смотрите также

  • method_exists() — Проверяет, существует ли метод в данном классе
  • is_callable() — Проверяет, что значение может быть вызвано как функция в текущей области видимости
  • get_defined_functions() — Возвращает массив всех определённых функций
  • class_exists() — Проверяет, был ли объявлен класс
  • extension_loaded() — Определяет, загружен ли модуль

User Contributed Notes 23 notes

You can use this function to conditionally define functions, see: http://php.net/manual/en/functions.user-defined.php

For instance WordPress uses it to make functions «pluggable.» If a plugin has already defined a pluggable function, then the WP code knows not to try to redefine it.

But function_exists() will always return true unless you wrap any later function definition in a conditional clause, like if()<. >. This is a subtle matter in PHP parsing. Some examples:

if ( function_exists ( ‘foo’ )) <
print «foo defined\\n» ;
> else <
print «foo not defined\\n» ;
>
function foo () <>

if ( function_exists ( ‘bar’ )) <
print «bar defined\\n» ;
> else <
print «defining bar\\n» ;
function bar () <>
>
print «calling bar\\n» ;
bar (); // ok to call function conditionally defined earlier

print «calling baz\\n» ;
baz (); // ok to call function unconditionally defined later
function baz () <>

qux (); // NOT ok to call function conditionally defined later
if (! function_exists ( ‘qux’ )) <
function qux () <>
>
?>
Prints:
foo defined
defining bar
calling bar
calling baz
PHP Fatal error: Call to undefined function qux()

Any oddities are probably due to the order in which you include/require files.

It should be noted that the function_exists check is not relative to the root namespace. This means that the namespace should be appended to the check:

if (! function_exists ( __NAMESPACE__ . ‘\example’ ))

The confusion expressed in some of the submissions here arise because functions declared outside conditional blocks are defined as the code is loaded and are thus callable and exist wherever in the code they are declared, whereas those declared inside a condition block are not defined until that block is executed. Thus:

however because those inside a conditional are defined as they are encountered during code execution

yields: Fatal error: Uncaught Error: Call to undefined function foo()

PHP supports nested function based on certain criteria.

Please look over the code.

function Audio()
echo «Plugged Audo 5.1:
«;
function Volume()
echo «Volume controls:
«;
function Equalizer()
echo «Equalize Bands:
«;
>
>
>
//Call to nested functions
Audio();
Volume();
Equalizer();

if(function_exists(‘Volume’)):
echo «TRUE»;
else:
echo «FALSE»;
endif;

Case 1: //Result :Works Well
———
Audio();
Volume();
Equalizer();

Case 2: //Results Notice Error. Root function Audio must be called first.
———
Volume();

Case 3: //Results Error. Root function Volume must be called.
———
Audio();
Equalizer();

Note :
The nested function should be called based on their order used.
In our example when Audio is not called and instantly when we try to call Volume puts under error.

Even though there is an possibility to use nested functions in PHP. It looks overhead to do so. Better to avoid in logical ground of script.

function_exists will return false for functions disabled with the disable_functions ini directive. However those functions are still declared so trying to define them yourself will fail.

if(! function_exists ( ‘readfile’ )) <
function readfile ( $file ) <
$handle =@ fopen ( $cache , «r» );
echo @ fread ( $handle , filesize ( $file ));
@ fclose ( $handle );
>
>
?>

The above will issue a «Cannot redeclare readfile()» fatal error if readfile was disabled with disable_functions.

To prevent direct calls to included files i use the following technique.

In the main file create an empty function with a random name. Like so:

function hjudejdjiwe () < return true ; >
?>

Then check for the existence of this function within your include:

if (! function_exists ( ‘hjudejdjiwe’ )) < die( '!' ); >
?>

Simple but effective.

This is not going to go down as you might expect it should (even if you play smart and require/include_once):

if( function_exists ( ‘my_function’ ))
throw new Exception ( «‘my_function’ is already defined!» );
>

function my_function ()
// Do the work here
>
?>

This, however does work:

if( ! function_exists ( ‘my_function’ ))
function my_function ()
// Do the work here
>
>
else
throw new Exception ( «‘my_function’ is already defined!» );
>
?>

Does it have anything to do with PHP parse/execute phases or global/local scope or those curly brackets or something else, I have no idea, but the latter ugly son works, while the former bombs out claiming that ‘my_function’ is already defined.

Thought this might save someone a few minutes of debugging time.

If you use suhosin.executor.func.blacklist instead of disabled_functions in your php.ini, function_exists will return true for a disabled function. I used this to have the same beahviour with suhosin.executor.func.blacklist and disabled_functions:

function suhosin_function_exists ( $func ) if ( extension_loaded ( ‘suhosin’ )) $suhosin = @ ini_get ( «suhosin.executor.func.blacklist» );
if (empty( $suhosin ) == false ) $suhosin = explode ( ‘,’ , $suhosin );
$suhosin = array_map ( ‘trim’ , $suhosin );
$suhosin = array_map ( ‘strtolower’ , $suhosin );
return ( function_exists ( $func ) == true && array_search ( $func , $suhosin ) === false );
>
>
return function_exists ( $func );
>
?>

Functions within a function are better off as anonymous returns from create_function(), unless you want to be able to call it elsewhere.

However, I have used this in skinning: I use alert_box() to display certain errors, like a faulty SQL query. This simply calls display_alert(), which is defined in my skin scripts. However, alert_box() is sometimes called before I know which skin to load, so it has its own functionality which it uses if function_exists(‘display_alert’) returns false.

I would like to comment on the following post:

A note of caution: function_exists() appears to be case-insensitive (at least as of PHP 4.3.8). e.g.:

function MyCasedFunction () return true ;
>

// Will return true, even though casing is «wrong»
if ( function_exists ( «mYcAsEdFuNcTiOn» ))
echo «I see it!» ;
?>

I believe that function calls itself are case insensitve, so this function is returning a valid truth. PHP doesn’t care about cases.

i was wondering whether is_callable or function exists is faster when checking class methods.

my results when doing each operation 10000 times with a simple test class were the following:

is_callable: 0.28671383857727 seconds
function_exists: 0.14569997787476 seconds

(following tests have proved this to be true).

thus you can see, function_exists is twice as fast as is_callable.

// If you want to chack if the function is enabled or disable in php.ini you can use this function:

function func_enabled ( $func ) $disabled = explode ( ‘,’ , ini_get ( ‘disable_functions’ ));
foreach ( $disabled as $disableFunction ) $is_disabled [] = trim ( $disableFunction );
>
if ( in_array ( $func , $is_disabled )) $it_is_disabled [ «m» ] = $func . ‘() has been disabled for security reasons in php.ini’ ;
$it_is_disabled [ «s» ] = 0 ;
> else $it_is_disabled [ «m» ] = $func . ‘() is allow to use’ ;
$it_is_disabled [ «s» ] = 1 ;
>
return $it_is_disabled ;
>
?>

// An example of how to use:

$if_is_disabled = func_enabled ( ‘exec’ ); // return Arrey
echo $if_is_disabled [ «m» ]; // return text value
echo ‘
‘ ;
echo $if_is_disabled [ «s» ]; // return 1 or 0
?>

I, too, was wondering whether is_callable or function exists is faster when checking class methods. So, I setup the following test:

function doTimes ( $start , $end )
$start_time = explode ( » » , $start );
$start_time = $start_time [ 1 ] + $start_time [ 0 ];
$end_time = explode ( » » , $end );
$end_time = $end_time [ 1 ] + $end_time [ 0 ];
$time = $end_time — $start_time ;
return $time ;
>

class test
function test ()
return true ;
>
>

$callableIsTrue = false ;
$startIsCallable = microtime ();
for( $i = 0 ; $i < 10000 ; $i ++)
if( is_callable (array( ‘test’ , ‘test’ ))) < $callableIsTrue = true ; >
>
$endIsCallable = microtime ();

$existsIsTrue = false ;
$startExists = microtime ();
for( $i = 0 ; $i < 10000 ; $i ++)
if( function_exists ( ‘test::test’ )) < $existsIsTrue = true ; >
>
$endExists = microtime ();

$timeIsCallable = doTimes ( $startIsCallable , $endIsCallable );
$timeExists = doTimes ( $startExists , $endExists );

echo «is_callable keyword»>.( $callableIsTrue ? «TRUE» : «FALSE» ). «, \n» ;
echo «function_exists keyword»>.( $existsIsTrue ? «TRUE» : «FALSE» ). «
\n» ;

echo «
Did 10000 is_callables in » . $timeIsCallable . » seconds» ;
echo «
Did 10000 function_exists in » . $timeExists . » seconds» ;
?>

This gives the output :

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0640790462494 seconds
Did 10000 function_exists in 0.0304429531097 seconds

So the fact that function_exists is twice as fast is slightly over shadowed by the fact that it doesn’t work on class methods, at least not as far as I can tell.

Источник

Php проверить доступность функции

Проверка доступности функции PHP

Ковырялся как-то в очередном сплойте, которым скрипткиддисы пытались проломить блог. Среди всякого говна нашел там интересную идею о проверке доступности функций PHP перед их вызовом. Реализация была такая же кривая, как и весь остальной код этих быдлохакеров, поэтому я переписал функцию проверки по-своему. Проверка выполняется тремя способами: анализом значения параметра disable_functions в файле php.ini, а также через функции PHP function_exists и is_callable. Использование всех трех способов проверки дает абсолютно точный результат.

  1. //—————————————————————————
  2. // Функция проверки существования и доступности другой функции PHP
  3. //—————————————————————————
  4. // Параметры: $func — строка имени функции
  5. // На выходе: true — функция есть и доступна для вызова,
  6. // false — функция недоступна по какой-либо причине
  7. //—————————————————————————
  8. function is_function_enabled ( $func )
  9. $func = strtolower ( trim ( $func ));
  10. if ( $func == » ) return false ;
  11. // Получить список функций, отключенных в php.ini
  12. $disabled = explode ( «,» ,@ ini_get ( «disable_functions» ));
  13. if (empty( $disabled ))
  14. $disabled =array();
  15. >
  16. else
  17. // Убрать пробелы и привести названия к нижнему регистру
  18. $disabled = array_map ( ‘trim’ , array_map ( ‘strtolower’ , $disabled ));
  19. >
  20. // Проверить доступность функции разными способами
  21. return ( function_exists ( $func ) && is_callable ( $func ) &&
  22. ! in_array ( $func , $disabled )
  23. );
  24. >

Функцию можно использовать, например, для проверки доступности нужных вам функций на различных бесплатных хостингах с ограничениями, или для выбора функции взаимодействия с операционной системой, типа shell_exec, если часть из них по какой-то причине запрещены.

Источник

Читайте также:  Javascript посмотреть свойства объекта
Оцените статью