The goal is to leave the input untouched in PHP 5.2.8. Let's have this sample text given in $_POST['example']:
a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( )
Let's have two simple scripts:
Script A:
<?php echo $_POST['example']; ?>
Script B:
<?php echo stripslashes($_POST['example']); ?>
Let's have four different configurations and corresponding output:
Case #1:
* magic_quotes_gpc = Off
* magic_quotes_sybase = Off
A: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )
Case #2
* magic_quotes_gpc = On
* magic_quotes_sybase = Off
A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( )
Case #3
* magic_quotes_gpc = On
* magic_quotes_sybase = On
A: a backslash ( ), a single-quote ( '' ), a double-quote ( " ) and a null character ( )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )
Case #4
* magic_quotes_gpc = Off
* magic_quotes_sybase = On
A: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )
Conclusions:
1) we do not need to do anything, if the magic_quotes_gpc is disabled (cases 1 and 4);
2) stripslashes($_POST['example']) only works, if the magic_quotes_gpc is enabled, but the magic_quotes_sybase is disabled (case 2);
3) str_replace("''", "'", $_POST['example']) will do the trick if both the magic_quotes_gpc and the magic_quotes_sybase are enabled (case 3);
<?php
function disable_magic_quotes_gpc()
{
if (TRUE == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc())
{
$mqs = strtolower(ini_get('magic_quotes_sybase'));
if (TRUE == empty($mqs) || 'off' == $mqs)
{
// we need to do stripslashes on $_GET, $_POST and $_COOKIE
&nbs.
lass="keyword">}
?>
Important notes:
1) arrays need to be processed recursively;
2) both stripslashes and str_replace functions always return strings, so:
* TRUE will become a string "1",
* FALSE will become an empty string,
* integers and floats will become strings,
* NULL will become an empty string.
On the other hand you only need to process strings, so use the is_string function to check;
3) when dealing with other (than GPC) data sources, such as databases or text files, remember to play with the magic_quotes_runtime setting as well, see, what happens and write a corresponding function, i.e. disable_magic_quotes_runtime() or something.
4) VERY IMPORTANT: when testing, remember the null character. Otherwise your tests will be inconclusive and you may end up with... well, serious bugs :)
php.theraven7.com
The goal is to leave the input untouched in PHP 5.2.8. Let's have this sample text given in $_POST['example']:
a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( )
Let's have two simple scripts:
Script A:
<?php echo $_POST['example']; ?>
Script B:
<?php echo stripslashes($_POST['example']); ?>
Let's have four different configurations and corresponding output:
Case #1:
* magic_quotes_gpc = Off
* magic_quotes_sybase = Off
A: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )
Case #2
* magic_quotes_gpc = On
* magic_quotes_sybase = Off
A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( )
Case #3
* magic_quotes_gpc = On
* magic_quotes_sybase = On
A: a backslash ( ), a single-quote ( '' ), a double-quote ( " ) and a null character ( )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )
Case #4
* magic_quotes_gpc = Off
* magic_quotes_sybase = On
A: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( )
B: a backslash ( ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )
Conclusions:
1) we do not need to do anything, if the magic_quotes_gpc is disabled (cases 1 and 4);
2) stripslashes($_POST['example']) only works, if the magic_quotes_gpc is enabled, but the magic_quotes_sybase is disabled (case 2);
3) str_replace("''", "'", $_POST['example']) will do the trick if both the magic_quotes_gpc and the magic_quotes_sybase are enabled (case 3);
<?php
function disable_magic_quotes_gpc()
{
if (TRUE == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc())
{
$mqs = strtolower(ini_get('magic_quotes_sybase'));
if (
TRUE == empty($mqs) || 'off' == $mqs)
{
// we need to do stripslashes on $_GET, $_POST and $_COOKIE
}
else
{
// we need to do str_replace("''", "'", ...) on $_GET, $_POST, $_COOKIE
}
}
// otherwise we do not need to do anything
}
?>
Important notes:
1) arrays need to be processed recursively;
2) both stripslashes and str_replace functions always return strings, so:
* TRUE will become a string "1",
* FALSE will become an empty string,
* integers and floats will become strings,
* NULL will become an empty string.
On the other hand you only need to process strings, so use the is_string function to check;
3) when dealing with other (than GPC) data sources, such as databases or text files, remember to play with the magic_quotes_runtime setting as well, see, what happens and write a corresponding function, i.e. disable_magic_quotes_runtime() or something.
4) VERY IMPORTANT: when testing, remember the null character. Otherwise your tests will be inconclusive and you may end up with... well, serious bugs :)
php.net
В Manual, цель stripslashes() состоит в том, чтобы исключить цитированную строку, что означает удаление обратного слэша, цитирующего символ. Обратите внимание: PHP не имеет символьного типа данных, поэтому все одиночные символы являются строками. Вы можете просмотреть этот примерный код, который демонстрирует, что эта функция оставляет косые черты, а также escape-последовательности с неизменяемыми неизменяемыми символами. Stripslashes() возникла, чтобы противостоять чрезмерному цитированию, вызванному тем, что ранее поддерживал PHP: магические кавычки.
В первые дни PHP, когда Расмус Лердорф работал с базами данных, которые требовали избежать символа одиночной кавычки, он нашел способ избежать скуки вручную добавления обратной косой черты для цитаты или выхода из этого символа; он создал магические цитаты:
... useful when mSQL or Postgres95 support is enabled since ... single quote has to be escaped when it is part of [a] ... query ... (See php.h in PHP/FI [php-2.0.1] )
В то время как магические кавычки не позволяют разработчикам использовать addlashes(), эта функция может автоматически указывать неправильно. Ввод формы со значением O'Reilly
будет отображаться как O'Reilly
. Применение stripslashes() исправило эту проблему. Хотя stripslashes() соответствовало его названию и удалял обратную косую черту, было недостаточно для решения всех проблем, связанных с магическими кавычками, функция, которая в конечном итоге была бы устаревшей в PHP5.3, а затем удалена с PHP5.4 (см. Manual).
Вы можете просмотреть цитируемые данные, если вы все еще используете версию PHP, которая поддерживает магические кавычки. Например, рассмотрим случай переменной $_GET, которая исходит из JavaScript, содержащего строку с кодировкой url, следующим образом:
location.href="next_page.php?name=O%27Riley"; // $_GET['name'] == O'Riley
Если вы должны были применить к $_GET [‘name’] либо addlashes(), либо mysqli_real_escape_string(), это значение переменной будет расширяться, содержащее еще две обратные косые черты:
O\'Riley
Предположим, что переменная была следующей в запросе на вставку. Обычно обратная косая черта цитируемого символа не сохраняется в базе данных. Но в этом случае запрос приведет к тому, что данные будут сохранены как:
O'Riley
Потребность в stripslashes() в настоящее время гораздо менее вероятна, но хорошо сохранить ее. Рассмотрим следующий JavaScript, содержащий вопиющую опечатку:
location.href="http://localhost/exp/mydog.php ?content=My%20dog%20doesn\\\%27t%20 like%20to%20stay%20indoors."
Используя stripslashes(), можно динамически исправить код следующим образом:
function removeslashes($string) { while( strpos( $string, "\" ) !== FALSE ) { $string = stripslashes( $string ); } return $string; } $text = htmlentities($_GET['content']); if (strpos($text,"\") !== FALSE ) { echo removeslashes( $text ); }
Примечание: stripslashes() не является рекурсивным.
qaru.site