import request variables php
PHP : import_request_ variables() function
Description
The import_request_variables() function is used to import GET/POST/Cookie variables into the global scope
Version:
Syntax:
Parameters:
Name | Description | Required / Optional | Type |
---|---|---|---|
string_types | Some predefined characters indicating which request variable is to be imported. ‘G’ or ‘g’ is used for specifying GET, ‘P’ or ‘p’ is used for specifying POST and ‘C’ or ‘c’ is used for specifying Cookie variables. Order of occurrence of the characters is important. Suppose you mention ‘gp’, POST variables will override the GET variables. If you use any other characters besides aforementioned characters, they are discarded. | Required | String |
prefix | A string which is added before the name of the imported variable. For example, if you have a post value named ’email’ and you supply a prefix ‘user’, the the imported variable name will be ‘user_email’.This is an optional parameter. | Optional | String |
Return value:
TRUE on success or FALSE on failure.
Value Type : Boolean.
Example :
See also
Previous: gettype
Next: intval
PHP: Tips of the Day
PHP: Showing all errors and warnings
Display errors could be turned off in the php.ini or your Apache configuration file.
You can turn it on in the script:
You should see the same messages in the PHP error log.
Php import_request_variable stopped working
Hey everyone I was getting the following error on my web page:
I removed that line and received the following error:
I removed that line and everything appears to be working fine now. Can anyone tell me what was happening with those 2 lines and if I should replace them with anything or should I just continue on without them.
Any guidance would be greatly appreciated.
2 Answers 2
I had this problem from before, the work around that i did to fix it i replaced code before with code after that I’ve written below, so don’t use import_request_variables it is deprecated in PHP 5.3 and in PHP 5.4 is removed as it is described in here http://uk3.php.net/import_request_variables, the following is the fix for the problem that i had:
Code After (Replaced the code above with the code below):
I wrote this replacement. It works for me. I hope it helps you. for example this URL : test.php?z=1
Not the answer you’re looking for? Browse other questions tagged php or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40232
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
PHP: функция import_request_ variable ()
Описание
Функция import_request_variables () используется для импорта переменных GET / POST / Cookie в глобальную область видимости.
Версия:
Синтаксис:
Параметры:
название | Описание | Необходимые / Необязательный | Тип |
---|---|---|---|
string_types | Некоторые предопределенные символы, указывающие, какая переменная запроса должна быть импортирована. «G» или «g» используется для указания GET, «P» или «p» используется для указания POST, а «C» или «c» используется для указания переменных Cookie. Порядок появления персонажей важен. Предположим, вы упомянули «gp», переменные POST переопределят переменные GET. Если вы используете любые другие символы, кроме вышеупомянутых символов, они отбрасываются. | необходимые | строка |
префикс | Строка, которая добавляется перед именем импортируемой переменной. Например, если у вас есть почтовое значение с именем «email» и вы указали префикс «user», импортированная переменная будет называться «user_email». Это необязательный параметр. | Необязательный | строка |
Возвращаемое значение:
ИСТИНА в случае успеха или ЛОЖЬ в случае неудачи.
Тип значения : логическое.
Пример :
Смотрите также
Предыдущий: gettype
Далее: Intval
Переменные извне PHP
HTML-формы (GET и POST)
Когда происходит отправка данных формы PHP-скрипту, информация из этой формы автоматически становится доступной ему. Существует несколько способов получения этой информации, например:
Пример #1 Простая HTML-форма
С версии PHP 5.4.0, есть только два способы получить доступ к данным из HTML форм. Доступные сейчас способы приведены ниже:
Пример #2 Доступ к данным из простой HTML POST-формы
В старых версиях PHP также существовало несколько других способов. Они приведены ниже. Смотрите также список изменений внизу страницы.
Пример #3 Старые способы получения пользовательских данных
// ВНИМАНИЕ: эти методы больше НЕ поддерживаются.
Точки и пробелы в именах переменных преобразуется в знаки подчеркивания. Например, станет $_REQUEST[«a_b»].
PHP также понимает массивы в контексте переменных формы (смотрите соответствующие ЧАВО). К примеру, вы можете сгруппировать связанные переменные вместе или использовать эту возможность для получения значений списка множественного выбора select. Например, давайте отправим форму самой себе, а после отправки отобразим данные:
Пример #4 Более сложные переменные формы
Имена переменных кнопки-изображения
При отправке формы вместо стандартной кнопки можно использовать изображение с помощью тега такого вида:
HTTP Cookies
Если вы хотите присвоить множество значений одной переменной cookie, вы можете присвоить их как массив. Например:
Обратите внимание, что cookie заменит предыдущую cookie с тем же именем в вашем браузере, если только путь или домен не отличаются. Так, для приложения корзины покупок вы, возможно, захотите сохранить счетчик. То есть:
Пример #5 Пример использования setcookie()
Точки в именах приходящих переменных
Как правило, PHP не меняет передаваемых скрипту имен переменных. Однако следует отметить, что точка не является корректным символом в имени переменной PHP. Поэтому рассмотрим такую запись:
По этой причине важно заметить, что PHP будет автоматически заменять любые точки в именах приходящих переменных на символы подчеркивания.
Определение типов переменных
import_request_variables
(PHP 4 >= 4.1.0, PHP 5 import_request_variables — Import GET/POST/Cookie variables into the global scope
Description
Imports GET/POST/Cookie variables into the global scope. It is useful if you disabled register_globals, but would like to see some variables in the global scope.
This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Parameters
Using the types parameter, you can specify which request variables to import. You can use ‘G’, ‘P’ and ‘C’ characters respectively for GET, POST and Cookie. These characters are not case sensitive, so you can also use any combination of ‘g’, ‘p’ and ‘c’. POST includes the POST uploaded file information.
Note that the order of the letters matters, as when using «GP«, the POST variables will overwrite GET variables with the same name. Any other letters than GPC are discarded.
Return Values
Returns TRUE on success or FALSE on failure.
Examples
Example #1 import_request_variables() example
See Also
User Contributed Notes
Call me crazy, but it seems to me that if you use this function, even WITH the prefix, then you might as well just turn register_globals back on.
Sooner or later, somebody will find a «hole» with your prefixed variables in an un-initialized variable.
Better to import precisely the variables you need, and initialize anything else properly.
import_request_variables() is gone from PHP since version 5.4.0. A simple plug-in replacement it extract().
Can be replaced with:
extract($_REQUEST, EXTR_PREFIX_ALL|EXTR_REFS, ‘v’);
oops, a typo in my comment:
The last line in the second example (the on using the extract() function) should read:
$input = array(‘name’ => null, ‘age’ => 26) ;
reply to ceo AT l-i-e DOT com:
I don’t think it’s a risk, as all of your request variables will be tagged with the prefix. As long as you don’t prefix any of your internal variables with the same, you should be fine.