Php получить все переменные запроса

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 ‘

Читайте также:  Css padding list style type
‘ . 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 );
>

Читайте также:  Сортировка одномерного массива python

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» );
>
>

Читайте также:  Java interface and implementation

//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.’

‘;
>
>
>

Источник

Отправка данных на сервер

Самым простым способом передачи данных на сервер приложению PHP извне представляет передача данных через строку запроса.

Строка запроса представляет набор параметров, которые помещаются в адресе после вопросительного знака. При этом каждый параметр определяет название и значение. Например, в адресе:

http://localhost/user.php?name=Tom&age=36

Часть ?name=Tom&age=36 представляет строку запроса, в которой есть два параметра name и age . Для каждого параметра определено имя и значение, которые отделяются знаком равно. Параметр name имеет значение «Tom», а параметр age — значение 36. Друг от друга параметры отделяются знаком амперсанда.

Например, определим следующий скрипт user.php со следующим содержимым:

 if(isset($_GET["age"])) < $age = $_GET["age"]; >echo "Имя: $name 
Возраст: $age"; ?>

Когда мы вводим в адресную строку браузера некий адрес и нажимаем на оправку, то серверу отправляется запрос типа GET . В PHP по умолчанию определен глобальный ассоциативный массив $_GET , который хранит все значения, передаваемые в запроса GET. Используя ключи передаваемых данных, мы можем из массива $_GET получить передаваемые значения.

При отправки строки запроса ключами в этом массиве будут названия параметров, а значениями — значения параметров.

Например, в строке запроса передается параметр name=Tom . Соответственно, чтобы получить значение параметра name из запроса, обращаемся по соответствующему ключу:

Однако стоит учитывать, что в адресной строке необязательно будет использоваться строка запроса или конкретно данный параметр. Поэтому перед получением значения параметра сначала смотрим, а передан ли вообще такой параметр:

Теперь обратимся к этому скрипту, например, так http://localhost/user.php?name=Tom&age=36 :

Массив <img decoding=

Оцените статью