|
|
addslashes (PHP 3, PHP 4, PHP 5) addslashes -- Экранирует спецсимволы в строке Описаниеstring addslashes ( string str )
Возвращает сроку str, в которой перед каждым
спецсимволом добавлен обратный слэш (\), например
для последующего использования этой строки в запросе к базе данных.
Экранируются одиночная кавычка ('), дойная кавычка
("), обратный слэш (\) и NUL
(байт NULL).
Функция addslashes() часто применяется при записи
в базу данных. Предположим, если нужно внести в базу данных имя
O'reilly, то символ ' должен
быть экранирован. В большинстве баз данных для этого используется
\, строка будет выглядеть как
O\'reilly. Заметьте, что сам символ
\ в базу данных записан не будет. Если директива
конфигурации magic_quotes_sybase
имеет значение on, то символ '
будет экранироваться добавлением еще одного '
вместо \.
Директива конфигурации
magic_quotes_gpc
по умолчанию имеет значение on, при этом функция
addslashes() автоматически применяется ко всем данным GET, POST,
и COOKIE. Не используйте addslashes() для данных,
обработанных magic_quotes_gpc,
чтобы избежать двойного экранирования. Для проверки состояния этой
директивы используется get_magic_quotes_gpc().
Пример 1. Пример использования addslashes() |
<?php
$str = "Is your name O'reilly?";
echo addslashes($str);
?>
|
|
См. также описание функций stripslashes(),
htmlspecialchars(),
quotemeta() и
get_magic_quotes_gpc().
David Harris
16-Aug-2007 10:40
If you need to make a PHP string literal, addslashes does work for this use because it escapes the double quote mark.
This works:
$data = "whatever";
$escaped = preg_replace('{([\'\\\\])}', '\\\\$1', $data);
$literal = '\'' . $escaped . '\'';
Lancelight
12-Aug-2007 01:29
The previous note should be array_add_slashes() at the top not array_strip_slashes(). I was playing with it when I pasted it in :/
Lancelight
11-Aug-2007 02:14
I found a very odd behavior when you combine addslashes and array_map in combination with an html form that has arrays in it. I dont know how to explain it other than showing the code for it. I believe this is probably a bug with array_map not picking up the array in the array that it received? Or maybe we just need a new PHP function for add/stripslashed that is array capable.
<?
$post_new = array_strip_slashes($_POST);
$_POST = array_map('stripslashes', $_POST);
//This is what the PHP array_map/addslashes does
echo "\$_POST: ";
print_r($_POST);
echo "\n<br>";
//This is what my work-around does
echo "\$post_new: ";
print_r($post_new);
?>
<form action=<? echo $_SERVER['PHP_SELF']; ?> method=POST>
<select name="categories[]" multiple>
<option value="number '1'"> number '1'</option>
<option value="number '2'"> number '2'</option>
<option value="number '3'"> number '3'</option>
<option value="number '4'"> number '4'</option>
<input type=submit name=submit value=submit>
</form>
<?
function array_add_slashes($array)
{
if (is_array($array))
{
foreach ($array AS $key => $value)
{
if (!is_array($value))
{
//echo "$key -> $value <br>";
$value = addslashes($value);
$key = addslashes($key);
$new_arr[$key] = $value;
}
if (is_array($value))
{
$new_arr[$key] = array_add_slashes($value);
}
}
}
return $new_arr;
}
function array_strip_slashes($array)
{
if (is_array($array))
{
foreach ($array AS $key => $value)
{
if (!is_array($value))
{
//echo "$key -> $value <br>";
$value = stripslashes($value);
$key = stripslashes($key);
$new_arr[$key] = $value;
}
if (is_array($value))
{
$new_arr[$key] = array_add_slashes($value);
}
}
}
return $new_arr;
}
?>
Nate from RuggFamily.com
24-May-2007 07:19
If you want to add slashes to special symbols that would interfere with a regular expression (i.e., . \ + * ? [ ^ ] $ ( ) { } = ! < > | :), you should use the preg_quote() function.
yoder2 at purdue dot edu
27-Apr-2007 12:23
to quote boris-pieper AT t-online DOT de, 15-Jan-2005 06:07,
Note: You should use mysql_real_escape_string() (http://php.net/mysql_real_escape_string) if possible (PHP => 4.3.0) instead of mysql_escape_string().
You may also want to us it instead of addslashes.
sam dot fullman at verizon
20-Mar-2007 03:37
There are other functions "kind of" like this one but this should help adding slashes to a form post which also contains arrays (and you can't access runtime quotes), or you need to add slashes to an array which is already stripped:
<?php
function addslashes_array($a){
if(is_array($a)){
foreach($a as $n=>$v){
$b[$n]=addslashes_array($v);
}
return $b;
}else{
return addslashes($a);
}
}
?>
note this does not add slashes to the keys - you could easily modify to do this..
Adrian C
02-Mar-2007 06:06
What happends when you add addslashes(addslashes($str))? This is not a good thing and it may be fixed:
function checkaddslashes($str){
if(strpos(str_replace("\'",""," $str"),"'")!=false)
return addslashes($str);
else
return $str;
}
checkaddslashes("aa'bb"); => aa\'bb
checkaddslashes("aa\'bb"); => aa\'bb
checkaddslashes("\'"); => \'
checkaddslashes("'"); => \'
Hope this will help you
joechrz at gmail dot com
19-Aug-2006 05:36
Here's an example of a function that prevents double-quoting, I'm surprised noone has put something like this up yet... (also works on arrays)
<?php
function escape_quotes($receive) {
if (!is_array($receive))
$thearray = array($receive);
else
$thearray = $receive;
foreach (array_keys($thearray) as $string) {
$thearray[$string] = addslashes($thearray[$string]);
$thearray[$string] = preg_replace("/[\\/]+/","/",$thearray[$string]);
}
if (!is_array($receive))
return $thearray[0];
else
return $thearray;
}
?>
Picky
24-May-2006 12:55
This function is deprecated in PHP 4.0, according to this article:
http://www.newsforge.com/article.pl?sid=06/05/23/2141246
Also, it is worth mentioning that PostgreSQL will soon start to block queries involving escaped single quotes using \ as the escape character, for some cases, which depends on the string's encoding. The standard way to escape quotes in SQL (not all SQL databases, mind you) is by changing single quotes into two single quotes (e.g, ' ' ' becomes ' '' ' for queries).
You should look into other ways for escaping strings, such as "mysql_real_escape_string" (see the comment below), and other such database specific escape functions.
luciano at vittoretti dot com dot br
31-Oct-2005 03:18
Note, this function wont work with mssql or access queries.
Use the function above (work with arrays too).
function addslashes_mssql($str){
if (is_array($str)) {
foreach($str AS $id => $value) {
$str[$id] = addslashes_mssql($value);
}
} else {
$str = str_replace("'", "''", $str);
}
return $str;
}
function stripslashes_mssql($str){
if (is_array($str)) {
foreach($str AS $id => $value) {
$str[$id] = stripslashes_mssql($value);
}
} else {
$str = str_replace("''", "'", $str);
}
return $str;
}
thisisroot at gmail dot com
26-Sep-2005 09:30
In response to Krasimir Slavov and Luiz Miguel Axcar:
There are several encoding schemes for inserting binary data into places it doesn't typically belong, such as databases and e-mail bodies. Check out the base64_encode() and convert_uuencode() functions for the details.
Krasimir Slavov kkslavov at yahoo dot com
16-Sep-2005 11:51
If you have problems with adding images or other binady data with addslashes() for php 4.3 >= use:
<?php
$search = array("\x00", "\x0a", "\x0d", "\x1a", "\x09");
$replace = array('\0', '\n', '\r', '\Z' , '\t');
$chrData .= str_replace($search, $replace, $Data );
?>
and put in your SQL field='$chrData' ! please remark quotes
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br)
01-Sep-2005 06:16
Hello,
If you are getting trouble to SGDB write/read HTML data, try to use this:
<?php
function unhtmlentities ($string) {
$trans_tbl =get_html_translation_table (HTML_ENTITIES );
$trans_tbl =array_flip ($trans_tbl );
return strtr ($string ,$trans_tbl );
}
$content = stripslashes (htmlspecialchars ($field['content']));
$content = unhtmlentities (addslashes (trim ($_POST['content'])));
$content = (! get_magic_quotes_gpc ()) ? addslashes ($content) : $content;
?>
unsafed
30-Apr-2005 08:23
addslashes does NOT make your input safe for use in a database query! It only escapes according to what PHP defines, not what your database driver defines. Any use of this function to escape strings for use in a database is likely an error - mysql_real_escape_string, pg_escape_string, etc, should be used depending on your underlying database as each database has different escaping requirements. In particular, MySQL wants \n, \r and \x1a escaped which addslashes does NOT do. Therefore relying on addslashes is not a good idea at all and may make your code vulnerable to security risks. I really don't see what this function is supposed to do.
gv
06-Nov-2004 05:23
Regarding the previous note using addslashes/stripslahes with regular expressions and databases it looks as if the purpose of these functions gets mixed.
addslahes encodes data to be sent to a database or something similar. Here you need addslashes because you send commands to the database as command strings that contain data and thus you have to escape characters that are special in the command language like SQL.
Therefore the use of addslahses on a regex does properly store the regex in the database.
stripslashes does the opposite: it decodes an addslashes encoded string. However, retrieving data from a database works differently: it does not go through some string interpretation because you actually retrieve your binary data in your variables. In other words: the data stored in your variable is the unmodified binary data that your database returned. You do not run stripslahes on data returned from a database. That way, the regexs are retrieved correctly, too.
This is different from other data exchange like urlencoded strings that you exchange with your browser. Here the data channel uses the same encodings in both directions: therefore you have to encode data to be sent and you have to decode data received.
percy at rotteveel dot ca
19-Oct-2004 08:08
Be very careful when using addslashes and stripslashes in combination with regular expression that will be stored in a MySQL database. Especially when the regular expression contain escape characters!
To store a regular expression with escape characters in a MySQL database you use addslashes. For example:
$l_reg_exp = addslashes(
|
|