Вывести все переменные get php

get_defined_vars

Эта функция возвращает многомерный массив, содержащий список всех определенных переменных, будь то переменные среды, сервера или определяемые пользователем переменные в пределах области, в которой вызывается get_defined_vars () .

Parameters

Эта функция не имеет параметров.

Return Values

Многомерный массив со всеми переменными.

Examples

Пример # 1 get_defined_vars () Пример

 $b = array(1, 1, 2, 3, 5, 8); $arr = get_defined_vars(); // print $b print_r($arr["b"]); /* print path to the PHP interpreter (if used as a CGI) * e.g. /usr/local/bin/php */ echo $arr["_"]; // print the command-line parameters if any print_r($arr["argv"]); // print all the server vars print_r($arr["_SERVER"]); // print all the available keys for the arrays of variables print_r(array_keys(get_defined_vars())); ?>

See Also

  • isset () — определяет, объявлена ​​ли переменная и отличается от нуля
  • get_defined_functions () — возвращает массив всех определенных функций
  • get_defined_constants () — возвращает ассоциативный массив с именами всех констант и их значений
PHP 8.2

(PHP 4 4.1.0,5,7,8)get_defined_constants Возвращает ассоциативный массив с именами всех и их значениями Возвращает имена и значения всех констант

(PHP 4 4.0.4,5,7,8)get_defined_functions Возвращает массив всех Получает массив всех определенных функций.

(PHP 4,5,7,8)get_extension_funcs Возвращает массив с именами функций модуля Эта функция возвращает имена всех функций,определенных модулем

(PHP 5,7,8)get_headers Собирает все отправленные сервером в ответ на HTTP-запрос get_headers()возвращает массив,содержащий отправленные сервером в ответ данные.

Источник

get_defined_vars

Эта функция возвращает многомерный массив, содержащий список всех определённых переменных, будь то переменные окружения, серверные переменные или переменные, определённые пользователем, в той области видимости, в которой была вызвана get_defined_vars() .

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

У этой функции нет параметров.

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

Многомерный массив со всеми переменными.

Примеры

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

$b = array( 1 , 1 , 2 , 3 , 5 , 8 );

// печатает $b
print_r ( $arr [ «b» ]);

/* печатает путь до интерпретатора PHP (при использовании режима CGI)
* например, /usr/local/bin/php */
echo $arr [ «_» ];

// печатает параметры командной строки, если они есть
print_r ( $arr [ «argv» ]);

// печатает все серверные переменные
print_r ( $arr [ «_SERVER» ]);

// печатает все доступные ключи для массивов переменных
print_r ( array_keys ( get_defined_vars ()));
?>

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

  • isset() — Определяет, была ли установлена переменная значением, отличным от null
  • get_defined_functions() — Возвращает массив всех определённых функций
  • get_defined_constants() — Возвращает ассоциативный массив с именами всех констант и их значений

User Contributed Notes 20 notes

Be aware of what get_defined_vars() function returns in different contexts:

— In global scope, a list of all defined variables, whether superglobals, command line arguments or user-defined variables
— In function scope, only a list of user-defined variables (both arguments and in-body definitions)
— In class/object method scope, does not return class/object properties;

Also, as of PHP 5.4, does not return $_ENV even where available.

For further details and scope tests/results, see https://github.com/php/doc-en/issues/1317

NOTE: when you call code by eval() PHP append self vars to result, they have «__» prefix («__source_code» and «__bootstrap_file» in PHP 7.3).

Fix:
function filter_eval_vars (array $vars ): array
foreach ( $vars as $key => $value ) if ( $key [ 0 ] === ‘_’ && $key [ 1 ] === ‘_’ ) unset( $vars [ $key ]);
>
>
return $vars ;
>

get_defined_vars() is very useful for importing many values at once
into another scope (Such as User-defined functions).

Below is an example for showing some of many values and their variable-names in a table.
(useful in debugging)

You can put this user-defined function at many places in your script
to show some values (values to be changed in loops)
to check if they are what they shall be there or not.

// Set «get_defined_vars()» to 2nd argument.
function get_value_table ( $name_array , $gdv ) $name_value_table = [];
foreach ( $name_array as $name ) :
if (! array_key_exists ( $name , $gdv )) :
$value = ‘undefined’ ;
elseif ( is_bool ( $gdv [ $name ])) :
$value = $gdv [ $name ]? ‘true’ : ‘false’ ;
elseif ( is_numeric ( $gdv [ $name ]) || is_string ( $gdv [ $name ])) :
$value = $gdv [ $name ];
elseif ( is_array ( $gdv [ $name ])) :
$value = ‘

' . print_r ( $gdv [ $name ], true ). '

‘ ;
else :
$value = ( PHP_VERSION_ID >= 80000 )? get_debug_type ( $gdv [ $name ]) : get_type ( $gdv [ $name ]);
endif;
$name_value_table [] = ‘$’ . $name . » . $value ;
endforeach;
return ‘

‘ . implode ( «\n» , $name_value_table ). ‘

‘ ;
> // (f) get_value_table()

$_1 = ‘a’ ;
$_2 = ‘b’ ;
$_3 = [ 1 , 2 ];
$_4 = false ;
$_5 = null ;

$name_array = [ ‘_1’ , ‘_2’ , ‘_3’ , ‘_4’ , ‘_5’ , ‘_6’ ];
$show_id = 1 ;

if ( $show_id === 1 ) :
echo get_value_table ( $name_array , get_defined_vars ());
endif;
/*
if $show_id === 1, only shows below.

$_2 = ‘c’ ;
if ( $show_id === 2 ) :
echo get_value_table ( $name_array , get_defined_vars ()); // $_2 c
endif;
# if $show_id === 2, $_2 turns «c».

Since get_defined_vars() only gets the variables at the point you call the function, there is a simple way to get the variables defined within the current scope.

// The very top of your php script
$vars = get_defined_vars ();

// Now do your stuff
$foo = ‘foo’ ;
$bar = ‘bar’ ;

// Get all the variables defined in current scope
$vars = array_diff ( get_defined_vars (), $vars );

echo ‘

' ; 
print_r ( $vars );
echo '

‘ ;
?>

A little gotcha to watch out for:

If you turn off RegisterGlobals and related, then use get_defined_vars(), you may see something like the following:

Array
(
[ GLOBALS ] => Array
(
[ GLOBALS ] => Array
* RECURSION *
[ _POST ] => Array()
[ _GET ] => Array()
[ _COOKIE ] => Array()
[ _FILES ] => Array()
)

[ _POST ] => Array()
[ _GET ] => Array()
[ _COOKIE ] => Array()
[ _FILES ] => Array()

)
?>

Notice that $_SERVER isn’t there. It seems that php only loads the superglobal $_SERVER if it is used somewhere. You could do this:

print ‘

' . htmlspecialchars ( print_r ( get_defined_vars (), true )) . '

‘ ;
print ‘

' . htmlspecialchars ( print_r ( $_SERVER , true )) . '

‘ ;
?>

And then $_SERVER will appear in both lists. I guess it’s not really a gotcha, because nothing bad will happen either way, but it’s an interesting curiosity nonetheless.

Insert this at point of interest; add keys of unwanted 1st dim variables to 2nd param of array_diff_key
echo ‘

defined_except ' ; var_dump ( array_diff_key ( get_defined_vars (), [ 'GLOBALS' => 0 , '_SERVER' => 0 ])); echo ' ' . basename ( __FILE__ ). ':' . __LINE__ . '

‘ ; #die;
?>

Reference variables are returned by reference (tested on PHP 5.5.11):
$a = null ;
$b = & $a ;
get_defined_vars ()[ ‘b’ ] = 4 ;
var_dump ( $b ); // int(4)
?>

get_defined_vars() returns all variables — locally defined vars and global vars (well actually only super globals). If you need local vars only — for example you need to get variables from a file — let’s say config.php and you don’t want a missing value to be replaced with a global defined somewhere else.

/**
* Filters out global vars from get_defined_vars() in order to get local vars only
* @param array $localVars pass get_defined_vars() here
*
* @return array local vars only
*/
function removeGlobals (array $localVars ) return array_diff_key ( $localVars , $GLOBALS );
>

define ( ‘CONFIG_FILE_PATH’ , ‘/path/to/config.php’ );
function readConfig () require CONFIG_FILE_PATH ;
$config = removeGlobals ( get_defined_vars ());
return $config ;
>

Here is a function which generates a debug report for display or email
using get_defined_vars. Great for getting a detailed snapshot without
relying on user input.

function generateDebugReport ( $method , $defined_vars , $email = «undefined» ) // Function to create a debug report to display or email.
// Usage: generateDebugReport(method,get_defined_vars(),email[optional]);
// Where method is «browser» or «email».

// Create an ignore list for keys returned by ‘get_defined_vars’.
// For example, HTTP_POST_VARS, HTTP_GET_VARS and others are
// redundant (same as _POST, _GET)
// Also include vars you want ignored for security reasons — i.e. PHPSESSID.
$ignorelist =array( «HTTP_POST_VARS» , «HTTP_GET_VARS» ,
«HTTP_COOKIE_VARS» , «HTTP_SERVER_VARS» ,
«HTTP_ENV_VARS» , «HTTP_SESSION_VARS» ,
«_ENV» , «PHPSESSID» , «SESS_DBUSER» ,
«SESS_DBPASS» , «HTTP_COOKIE» );

$timestamp = date ( «m/d/y h:m:s» );
$message = «Debug report created $timestamp \n» ;

// Get the last SQL error for good measure, where $link is the resource identifier
// for mysql_connect. Comment out or modify for your database or abstraction setup.
global $link ;
$sql_error = mysql_error ( $link );
if( $sql_error ) $message .= «\nMysql Messages:\n» . mysql_error ( $link );
>
// End MySQL

if( $method == «browser» ) echo nl2br ( $message );
>
elseif( $method == «email» ) if( $email == «undefined» ) $email = $_SERVER [ «SERVER_ADMIN» ];
>

$mresult = mail ( $email , «Debug Report for » . $_ENV [ «HOSTNAME» ]. «» , $message );
if( $mresult == 1 ) echo «Debug Report sent successfully.\n» ;
>
else echo «Failed to send Debug Report.\n» ;
>
>
>
?>

I occasionally use this as a hack to convert arguments to an array where terseness is needed (dealing with legacy code, etc).

However in an object context it’ll also pull in $this.

Make sure to unset it. If you map it to properties or an array then setting the key this wont be an error.

I recommend using a wrapper function that strips this from the result.

for all those who don’t know how to us this function. copy and run this code in your computer .

note: you need to know what superglobals are.

$A = 5 ;
$B = 10 ;
$C = 15 ;
$D = 20 ;

var_dump ( $F ); //don’t use echo. it will show error

?>

Result : will show all superglobals status along with your defined
variables along with its values

Simple routine to convert a get_defined_vars object to XML.

function obj2xml ( $v , $indent = » ) <
while (list( $key , $val ) = each ( $v )) <
if ( $key == ‘__attr’ ) continue;
// Check for __attr
if ( is_object ( $val -> __attr )) <
while (list( $key2 , $val2 ) = each ( $val -> __attr )) <
$attr .= » $key2 =\» $val2 \»» ;
>
>
else $attr = » ;
if ( is_array ( $val ) || is_object ( $val )) <
print( » $indent < $key$attr >\n» );
obj2xml ( $val , $indent . ‘ ‘ );
print( » $indent \n» );
>
else print( » $indent < $key$attr >$val \n» );
>
>

//Example object
$x -> name -> first = «John» ;
$x -> name -> last = «Smith» ;
$x -> arr [ ‘Fruit’ ] = ‘Bannana’ ;
$x -> arr [ ‘Veg’ ] = ‘Carrot’ ;
$y -> customer = $x ;
$y -> customer -> __attr -> id = ‘176C4’ ;

Here’s a very simple function for debugging. It’s far from perfect but I find it very handy. It outputs the var value and the var name on a new line. The problem is it’ll echo any vars and their name if they share the same value. No big deal when debugging and saves the hassle of writing the HTML and var name when echoing a variable. (ev=echo variable). Using get_defined_vars() inside a function renames the var name to the functions variable so isn’t as useful for debugging. Of course, you’ll need access to the $GLOBALS array
function ev($variable) foreach($GLOBALS as $key => $value) if($variable===$value) echo ‘

‘.$key.’ — ‘.$value.’

‘;
>
>
>

Источник

Как вывести все параметры get запроса из стоки?

DmitriyEntelis

Выход вашего кода:
Array ( [u] => i [6] => 3 [a] => m [1] => [-] => 7 [h] => t [e] => 9 [l] => _ [%] => D [3] => 5 [0] => [] => [d] => 6 [2] => [O] => q [A] => d [V] => K [S] => t [L] => i [U] => n [M] => i [C] => o [F] => u [R] => e [W] => a [G] => o [T] => h )

DmitriyEntelis

DmitriyEntelis

Aliance

@WQP какой смысл выбирать решением код, работающий через циклы, при наличии нативной php функции, о которой я написал в своем варианте решения?

Aliance

OKrasnov

Они в виде массива и приходят $_GET
или на экран?

У меня есть строка и она очень большая, и из-за этого необходимо разбить её в массив. Вот пример строки: uid=63235608&vid=169266795&oid=-73675894&host=cs541407v4.vk.me/&vtag=e017915e98&ltag=l_478e5d4f&.

OKrasnov

Ну тогда со строкой много способов, включая поиск по шаблону. Но explode в два этапа. сначала по & потом по =. Это очень странно и если в строке встретятся эти символы в другом контексте, то все сломается.

Источник

Читайте также:  Can android run python scripts
Оцените статью