php flag magic quotes gpc off
Php flag magic quotes gpc off
The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.
Example #1 Disabling magic quotes server side
In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here’s an example to disable magic_quotes_gpc at runtime. This method is inefficient so it’s preferred to instead set the appropriate directives elsewhere.
Example #2 Disabling magic quotes at runtime
User Contributed Notes 10 notes
php_flag magic_quotes_gpc Off
php_value magic_quotes_gpc Off
Firstly, copy the server’s php.ini file to your domain’s web-root folder. To find the correct paths, use phpinfo() and look for «Configuration File (php.ini) Path» and «DOCUMENT_ROOT»
It’s unlikely you’ll have access to the php.ini via FTP, so instead run a script with a simple copy command (obviously inserting your paths):
exec(«cp /usr/local/php/etc/php.ini /home/LinuxPackage/public_html/php.ini);
Edit the now-accessible php.ini file, and add settings like ‘magic_quotes_gpc = off’ at the bottom (regardless of whether they’ve been set earlier in the file). I also set:
[PHP]
max_execution_time = 60
max_input_time = 90
memory_limit = 64M
post_max_size = 32M
upload_max_filesize = 31M
magic_quotes_gpc = Off
Finally add the below line to your web-root htaccess file, to make the local php.ini the web-root default (so you don’t need a copy in every script sub-folder):
SetEnv PHPRC /home/LinuxPackage/public_html/php.ini
Hope that helps a few people save some time!
P.S. Using the new php_ini_loaded_file() function the whole lot could be done in three lines:
Mike’s answer worked for me. The only thing that was different was finding the path to the php.ini file.
Configuration File (php.ini) Path said the path was /etc, but this wasn’t true. There was no php.ini there.
PHP’s magic quotes function has the strange behavior of not adding slashes to top level keys in GPC key/value pairs but adding the slashes in deeper level keys. To demonstrate, a URI of:
example.php?a’b[c’d]=e’f
produces:
array(«a’b» => array(«c\’d» => «e\’f»))
The current example for removing magic quotes does not do anything to keys, so after running stripslashes_deep, you would end up with:
array(«a’b» => array(«c\’d» => «e’f»))
Which, needless to say, is wrong. As if you had magic quotes off, it would have been:
array(«a’b» => array(«c’d» => «e’f»))
I have written a snippet of code compatible with PHP 4.0.0 and above that handles this correctly:
Php flag magic quotes gpc off
Что представляют собой «Волшебные Кавычки»?
Когда «Волшебные Кавычки» включены (активизированы), все ‘ (одиночные кавычки), « (двойные кавычки), \ (левый слэш) и NULL знаки автоматически экранируются левыми слэшами (\). Данный принцип аналогичен действию функции addslashes().
Существуют три директивы «Волшебных Кавычек»:
Затрагивает данные запросов HTTP (GET, POST, и COOKIE). Не может быть установлена в процессе работы PHP скрипта и установлена в on по умолчанию.
Если данная директива включена (on), большинство функций, которые возвращают данные из внешнего источника, включая базы данных и текстовые файлы, будут экранировать данные левыми слэшами (\). Может быть установлена во время выполнения PHP скрипта. По умолчанию директива установлена в off.
Если данная директива включена (on), одиночные кавычки экранируются двойными кавычками, вместо левых слэшей (\). Причем если данная директива установлена в on, это полностью отменяет установку директивы magic_quotes_gpc. Включение (on) обеих директив будет означать, что будут экранироваться только одиночные кавычки двойными кавычками («). Двойные кавычки («), левые слэши (\) и NULL останутся нетронутыми.
Смотрите также описание функции ini_get(), которая позволяет получить значения упомянутых директив.
Зачем использовать «Волшебные Кавычки»?
1. Это полезно для начинающих программистов PHP
«Волшебные кавычки» были добавлены в PHP, чтобы помочь начинающим программистам языка PHP избегать фатальных последствий для безопасности системы при ошибках в коде написанных PHP скриптов, причем автоматически, без участия самого программиста. Хотя риск SQL инъекций при этом остается возможным, степень такого риска сводится к минимуму.
2. Это довольно удобно
Для того, чтобы вставлять данные в базу данных, «Волшебные Кавычки» можно не добавлять функцией addslashes() на всех Get, Post, и Cookie запросах, а делать это автоматически.
Почему не нужно использовать «Волшебные Кавычки»?
Включение экранирования и его выключение влияет на вашу мобильность. Используйте функцию get_magic_quotes_gpc() для проверки активной установки конфигурации «Волшебных Кавычек».
Поскольку не каждая часть экранируемых данных используется в базах данных, существует потеря производительности PHP, поскольку обработка данных на предмет необходимости «экранирования» влечет за собой некоторую дополнительную нагрузку на систему. При необходимости произвести «экранирование» данных вы можете просто обращаться к соответствующим функциям (таким как addslashes()) и не пребегать к автоматическому экранированию «Волшебными Кавычками».
Вообще, при установке рекоммендуемых значений директив в файле конфигурации php.ini, автоматическое использование «Волшебних Кавычек» отключено, именно по соображениям производительности.
Поскольку не все данные нуждаются в экранировании, часто раздражет видеть «Волшебные Кавычки» там, где их не должно быть.Например, используя скрипт посылки электронной почту из формы, и видя связку \’ в полученном сообщении электронной почты. А для устанения данной неприятности вам нужно будет часто прибегать к использованию функции stripslashes(), что, согласитесь, не очень удобно.
Отключение «Волшебных Кавычек»
Директива magic_quotes_gpc может быть выключена (off) только на системном уровне, но не во время исполнения скрипта. Так что функция ini_set() в данной ситуации вам не поможет.
Пример 1. Отключение «Волшебных Кавычек» на стороне сервера
Данный пример показывает как установить значение директивы «Волшебных Кавычек» в Off в файле конфигурации php.ini.
Если вам недоступно изменение конфигурационного файла PHP, то вы можете использовать в таком случае .htaccess веб-сервера Apache, используя следующий метод:
Если вам интересен небольшой переносимый PHP код, который позволяет конфигурировать «Волшебные Кавычки» во время исполнения скрипта определенным образом, то для вас ниже приведен листинг этого кода. Этот метод неэффективен, но иногда его использование может помочь. Итак, отключение magic_quotes_gpc во ремя исполнения скрипта PHP.
Пример 2. Альтернативный способ отключения «Волшебных Кавычек» во время исполнения скрипта
Joomla magic quotes gpc off
Вскоре разработчики пришли к выводу, что такой подход не удобен, но хитрые хостеры предпочитают по умолчанию все-таки включать её, по понятным причинам, и не всегда дают возможность ее убрать.
После версии PHP 5.3 данная опция перешла в разряд deprecated(устаревшая), а вскоре и вовсе будет выпилена из php.
magic_quotes_gpc и joomla
А в Joomla до 3-ьей версии magic_quotes_gpc проверялась внутри самого фрэймворка и автоматически предпринималось разэкранирование, в случае, если она была включена. В Joomla 3 эту самую проверку убрали и вместо этого добавили требование версии php > 5.3 при установке. По мне сомнительное решение. Но нытьем проблему не решить, поэтому начинаем делать.
Отключение magic_quotes_gpc
Дописываем в htaccess файл строчку:
php_flag magic_quotes_gpc off
Способ второй. php.ini
Самый правильный способ, но на shared-хостингах как правило не подпускают к настройкам php. Зачастую доступ к php.ini дается через панель хостинга. В остальных случаях, всё просто:
Открываем php.ini, дописываем или редактируем строчку
Способ третий. Хардкод
добавляем эти строки в начало файлов index.php и administrator/index.php
Просто проходимся по массивам входных данных и убираем лишнее. Этот поможет в случае, если необходимо перенести готовый сайт на хостинг, где эта опция включена и это навсегда. Так и случилось со мной, один из моих сайтов на joomla расположился на godaddy, где по умолчанию magic_quotes_gpc включено, а возможности отключить нет.
get_magic_quotes_gpc
get_magic_quotes_gpc — Получение текущего значения настройки конфигурации magic_quotes_gpc
Эта функция УСТАРЕЛА, начиная с PHP 7.4.0 и была УДАЛЕНА, начиная с PHP 8.0.0. Использовать эту функцию крайне не рекомендуется.
Описание
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Список изменений
Версия | Описание |
---|---|
7.4.0 | Функция объявлена устаревшей. |
Смотрите также
User Contributed Notes 10 notes
@ dot dot dot dot dot alexander at gmail dot com
I suggest replacing foreach by «stripslashes_deep»:
Re: php at kaiundina dot de (03-Feb-2005 02:18)
1. magic_quotes_gpc=on/off and magic_quotes_sybase=on/off
I made test and your function worked right.
These were the names I used:
name=»a»
name=»b.b b\b»
name=»c[c.1]»
name=»c[c 2]»
name=»c[c\3]»
name=»c.c c[c.’ 4]»
name=»c ‘ c[c»4]»
name=»d»[d»1]»
(I used » because I don’t know other way to put » into the name)
and the user-input value:
a ‘ » \ \’ \» \\ a
2. > 17) The chars ‘.’, ‘ ‘ are always replaced by ‘_’ when used in keys.
This is true only for the top-level keys, such as «b.b b\b», «c.c c» and «c ‘ c» above. The second-level key «[c.’ 4]» was not changed to [c_’_4] but was escaped acording to how magic_quites_XXX are set.
These magic_quotes are really black magic 🙁
Here’s what I came up with to remove magic quotes from request data.
Replaces two single-quotes with one if magic_quotes_sybase are on, otherwise it just strips slashes.
Note that the `foreach` style makes this work only with PHP 5 and above.
Escaping of key-strings in GPC-arrays behave different to the escaping of their values.
First I expected that keys in submitted gpc-arrays are never escaped.
Anyway. After I saw escaped keys, I assumed they’re escaped according to the settings of magic quotes.
. it’s even worse.
It took me over 2 days of testing to figure out the exact behavior and creating two functions (one for each php-version) that strips slashes reliably from any array submitted to a script. Hope this saves someones time and nerves.
== legend for possible case combinations ==
Px = php version we’re using
P4 = php 4.3.9
P5 = php 5.0.2
MQ = MagicQuotes GPC
+MQ = magic quotes enabled
-MQ = magic quotes disabled
AK = ArrayKey
+AK = the value of the key is another array (i.e. is_array($_GET[‘myKey’]) == true)
-AK = the value is a normal string (i.e. is_string($_GET[‘myKey’]) == true)
== legend for possible results ==
KE = KeyEscaping
+KE = control chars are prefixed with a backslash
-KE = key is returned as submitted and needn’t to be stripped
VE = ValueEscaping (doesn’t apply for array as value)
+VE = control chars are prefixed with a backslash
-VE = value is returned as submitted and needn’t to be stripped
Example (rule 15):
When running under php 5.0.2 having magic quotes disabled, gpc-keys on top level containing strings are escaped while their associated values are not.
== The following function will strip GPC-arrays for php 4.3.9 ==
When you work with forms and databases you should use this concept:
$query=’INSERT INTO users SET fullname=»‘.add_slashes($_POST[‘fullname’]).'»‘;
insert_into_db($query);
2.When reading a previously submitted input from DB use html_special_chars to display an escaped result!
read_db_row(‘SELECT fullname FROM users’);
echo ‘
this way you safely store and work with the original(unescaped) data.
> «If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc.»
This «note» is a bit misleading. magic_quotes_sybase will only override the escaping method used on Get/Post/Cookie data if magic_quotes_gpc is already enabled. If magic_quotes_gpc is not enabled then magic_quotes_sybase will have no effect here.
A few of the other comments are therefore incorrect in determining when to «stripslashes» from the input, by «stripping slashes» when either magic_quotes_gpc OR magic_quotes_sybase is enabled. You should only stripslashes() when magic_quotes_gpc is enabled since that is the only time when slashes are automatically added.
stripslashes() is also magic_quotes_sybase aware, so you don’t need to do anything special (ie. write a custom function to handle this situation as another comment suggests) when magic_quotes_sybase is enabled. When magic_quotes_sybase is enabled, stripslashes() does not actually strip any slashes, but instead unescapes single-quotes that are escaped with single-quotes only.
magic_quotes_sybase does however influence the escaping (and unescaping) method used by addslashes() and stripslashes() respectively, regardless of whether magic_quotes_gpc (or magic_quotes_runtime) is enabled.
Regarding the three main strip methods as found below (two using foreach, 1 using the json method), I’ve done a little benchmarking using ‘true’ profiling (using a registered tickhandler where declare(ticks=1)).
I wondered whether or not json would not be terribly slow.
I won’t discuss the profiler, but will suffice with the following statement, followed by the used code to benchmark:
The json method was by FAR the quickest (contrary to what I’d thought), so if you need a speedy process, use that!
?>
My output (PHP 5.3.1, win32):
[TickProfiler::tick] => Array
(
[time] => 0.76188707351685
[calls] => 46001
)
[TickProfiler::Register] => Array
(
[time] => 3.0994415283203E-5
[calls] => 1
)
[strip_json] => Array
(
[time] => 0.025638580322266
[calls] => 1000
)
[strip_deep1] => Array
(
[time] => 0.40303444862366
[calls] => 36000
)
[strip_deep2] => Array
(
[time] => 0.14928555488586
[calls] => 9000
)
As can be seen above, using json speeds output by at least a factor of 5 (nearly 6).
Just wanted to share this 😀
Do note the strip_json function has two LOC instead of a plain return statement, otherwise it wouldn’t get picked up by the tickprofiler (it would return from the code immediately, never reaching the profiler)!
Usage of the return statement in strip_deep2 is not needed, as the argument is passed by reference.
A new test showed that the time penalty for this is about 0.09 seconds.
This actually means that the factor between strip_deep2 vs strip_json is only about 2.
Still, strip_json would be about twice as fast as strip_deep2
How to turn off magic quotes on shared hosting?
I want to turn off PHP’s magic quotes. I don’t have access to php.ini.
How do I turn magic quotes off?
13 Answers 13
As per the manual you can often install a custom php.ini on shared hosting, where mod_php isn’t used and the php_value directive thus leads to an error. For suexec/FastCGI setups it is quite common to have a per-webspace php.ini in any case.
I don’t think O (uppercase letter o) is a valid value to set an ini flag. You need to use a true/false, 1/0, or «on»/»off» value.
EDIT
After checking the list of ini settings, I see that magic_quotes_gpc is a PHP_INI_PERDIR setting (after 4.2.3), which means you can’t change it with ini_set() (only PHP_INI_ALL settings can be changed with ini_set() )
While I can’t say why php_flag is giving you 500 Internal Server Error s, I will point out that the PHP manual has an example of detecting if magic quotes is on and stripping it from the superglobals at runtime. Unlike the others posted, this one is recursive and will correctly strip quotes from arrays:
Update: I noticed today that there’s a new version of the following code on the PHP manual that uses references to the super-globals instead.
This will solve the problem of getting «Class ‘PDO’ not found» when you create a local php.ini file.
If you can’t turn off magic quotes using the htaccess file (for reasons already given by Pete Bailey) just:
magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off
extension=pdo.so
extension=pdo_mysql.so
Save it to the directory/ies in which your scripts are executing.
Obviously you need to move the ini file to this location of it’s not there already.
Hope that saves someone the 2 hours it’s just taken me!
Apache is thus correct giving you a server error: it doesn’t know about the meaning of php_flag unless the PHP module is loaded. A CGI binary is to Apache an external program instead, and you can’t configure it from within Apache.