search for in the  
<addcslashesbin2hex>
Last updated: Thu, 19 May 2005

addslashes

(PHP 3, PHP 4, PHP 5)

addslashes -- Quote string with slashes

Description

string addslashes ( string str )

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. Most databases do this with a \ which would mean O\'reilly. This would only be to get the data into the database, the extra \ will not be inserted. Having the PHP directive magic_quotes_sybase set to on will mean ' is instead escaped with another '.

The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this.

Example 1. An addslashes() example

<?php
$str
= "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

See also stripslashes(), htmlspecialchars(), quotemeta(), and get_magic_quotes_gpc().



User Contributed Notes
addslashes
yet another user
07-May-2005 04:26
@unsafed: well it worked great for me adding records to my "storyDB":

$stTitle = addslashes($wholestory[$storyid][titel]);
$stInhalt = addslashes($wholestory[$storyid][inhalt]);
$aktueller_eintrag = "INSERT INTO $dbTable (titel, inhalt) VALUES ('$stTitle', '$stInhalt');";
$eintragInDB = mysql_query($aktueller_eintrag);

withot function addslashes i had problems with chars like the single quotes, and the query didn't work.

but with this function everything worked fine...

greetz
unsafed
30-Apr-2005 11: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.
caya
24-Feb-2005 09:06
What I said is that if get_magic_quotes_gpc() is 1 (on) then the Get, Post and Cookie data is dirty (you have something in memory the user didn't type). You need to clean it up by calling stripslashes.

The code I sent was wrong, please read the code in get_magic_quotes_gpc(), which is the place I should put this comment in the first place :-)
akeel_din at sbcglobal dot net
13-Feb-2005 02:17
caya's code should read:

if (!get_magic_quotes_gpc()) {
...
caya
06-Feb-2005 09:13
Unfortunately magic quotes is the default and violates a simple principle: what the user types is what you get.

If you want to follow that principle the following code snippet may be useful:

function cleanData() {
   foreach($_GET as $k => $v)
     $_GET[$k] = stripslashes($v);
   // likewise for $_POST, $_COOKIE
}

...

if (get_magic_quotes_gpc()) {
   cleanData();
}

You will need to add this to every page... sorry. But this is sometimes easier than convincing a webhosting company to change the settings...(if you use a front-controller pattern it's a lot easier...)

With this principle, then you always have in memory real data.

When generating HTML, you may need then to do htmlentities(...), as you are moving from the 'php data world' to the 'html data world', but you are playing on the safe side.

Same analysis apply to generating SQL sentences...
caya
06-Feb-2005 09:13
Unfortunately magic quotes is the default and violates a simple principle: what the user types is what you get.

If you want to follow that principle the following code snippet may be useful:

function cleanData() {
   foreach($_GET as $k => $k)
     $_GET[$k] = stripslashes($k);
   // likewise for $_POST, $_COOKIE
}

...

if (get_magic_quotes_gpc()) {
   cleanData();
}

You will need to add this to every page... sorry. But this is sometimes easier than convincing a webhosting company to change the settings...(if you use a front-controller pattern it's a lot easier...)

With this principle, then you always have in memory real data.

When generating HTML, you may need then to do htmlentities(...), as you are moving from the 'php data world' to the 'html data world', but you are playing on the safe side.

Same analysis apply to generating SQL sentences...
sundevil at hexagonomistico dot com
04-Feb-2005 04:12
Hey! if you will use a database to store data that will only be accessible through a web page i.e. just for web purposes, you may use other kind of filters. I recommend to use first the addcslashes() function, in order to escape line feeds and then to replace those line feeds by the corresponding html tag. And finally use the htmlentities() function in order to replace those annoying quotes or other characters by their corresponding html tag.
For example, data stored in a textarea as:

"hola"
<hola>
más niños

May be filtered using: addcslashes($textarea, "\n,\\"), as:
"Hola"\n<hola>\nmás niños

Then, using: htmlentities($textarea,ENT_QUOTES), should return:
&quot;Hola&quot;\n&lt;hola&gt;\nm&aacute;s ni&ntilde;os
(Which has just converted the special characters in their html tags)

Finally, using: str_replace('\n','<br>',$textarea), may add a html line feed everytime it encounters a \n. So, when you retrieve data from the database you will be able to use it as html code just as typed!
(perhaps retrieving into a textarea gives a little more problem! Oops!)
josh at gitlinfamily dot com
05-Jan-2005 09:37
Here's a (very simple) way to determine if a string needs to be escaped by addslashes:

<?php
function string_needs_addslashes($str)
{
     if ((
$qp = strpos($str,'\'')) !== false)
     {
         if (
$sp<1 || $str[$qp-1] != '\\')
               return
true;
         else
               return
string_needs_addslashes(substr($str,$sp+1));
     }
     return
false;
}
?>

The theory being, if a single quote is found and is not prefaced by a slash, then the string is not safe and needs to be escaped before database entry.
gv
06-Nov-2004 08: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 11: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( “[\x00-\x1F]” );

After this the variable $l_reg_exp will contain: [\\x00-\\x1F].

When you store this regular expression in a MySQL database, the regular expression in the database becomes [\x00-\x1F].

When you retrieve the regular expression from the MySQL database and apply the PHP function stripslashes(), the single backslashes will be gone!

The regular expression will become [x00-x1F] and your regular expression might not work!
mark at hagers dot demon dot nl
27-Sep-2004 06:34
I was stumped for a long time by the fact that even when using addslashes and stripslashes explicitly on the field values double quotes (") still didn't seem to show up in strings read from a database. Until I looked at the source, and realised that the field value is just truncated at the first occurrence of a double quote. the remainder of the string is there (in the source), but is ignored when the form is displayed and submitted.

This can easily be solved by replacing double quotes with "&quot;" when building the form. like this:
$fld_value =  str_replace ( "\"", "&quot;", $src_string ) ;
The reverse replacement after the form submission is not necessary.
hazy underscore fakie at ringwraith dot org
12-Jul-2003 02:23
Note that when using addslashes() on a string that includes cyrillic characters, addslashes() totally mixes up the string, rendering it unusable.
phil at internetprojectmanagers dot com
09-Apr-2003 09:46
re: problem with mcrypt, addslashes and mysql

Here is my solution to the problem of characters from mcrypt creating issues with mysql calls (due to characters which aren't cleaned up by addslashes).

Solution: simply convert your encryption string to hex, then back to binary when you are ready to decrypt.

<?php
// ie.
$encrypted = addslashes($string);   
$encrypted = bin2hex($encrypted);

// ... then:
$decrypted = hex2bin($encrypted);
$decrypted = stripslashes($decrypted);

// where hex2bin() is:
function hex2bin($hexdata) {
 
$bindata="";
 
  for (
$i=0;$i<strlen($hexdata);$i+=2) {
  
$bindata.=chr(hexdec(substr($hexdata,$i,2)));
  }

  return
$bindata;
}
?>

One word of caution: this will increase the length of your initial data string, so you will need to increase the field length for your mysql database.

Cheers, Phil
PS. I knew that I'd eventually be able to give something back to the site!
phil at internetprojectmanagers dot com
09-Apr-2003 07:47
re: encryption, addslashes and mysql

Note that mcrypt encryption may add in an apostrophe from the ascii table which cannot be protected by addslashes. It may not even be on your keyboard.

Because encryption strings are random, you may not discover it unless you test (or stumble?) on the correct sequence which inserts an apostrophe in the encrypted string.

This means that testing is even more important where encryption is concerned. If I create a solution I'll post it here.

Phil
steve at teamITS dot com
18-Jan-2003 08:53
For thelogrus, my testing shows the opposite--that a slashed string is stored correctly by MySQL.  Consider

insert into test (field1) values ('test\'test')

...which is stored as "test'test".  If you were posting "Sir'Weaser" from a form to your script and have magic_quotes_gpc on, then the string is slashed already so if you run addslashes() again you will be entering "Sir\\'Weaser" into MySQL.  In that case "Sir\'Weaser" would be the correct output.

In summary, addslashes() is not necessary if magic_quotes_gpc is on.
mike at gyrate dot org
13-Jan-2003 05:05
[Editor's note: See also the php.ini configuration magic_quotes_sybase at the URL http://www.php.net/manual/en/ref.sybase.php]

please note that addslashes will NOT work with mssql, since mssql does not use the backslash character as an escape mechanism.  just double your quotes instead.  or use this:

<?php
function mssql_addslashes($data) {
  
$data = str_replace("'", "''", $data);
   return
$data;
}
?>
hoskerr at nukote dot com
12-Nov-2002 06:16
Beware of using addslashes() on input to the serialize() function.  serialize() stores strings with their length; the length must match the stored string or unserialize() will fail. 

Such a mismatch can occur if you serialize the result of addslashes() and store it in a database; some databases (definitely including PostgreSQL) automagically strip backslashes from "special" chars in SELECT results, causing the returned string to be shorter than it was when it was serialized.

In other words, do this...

<?php
$string
="O'Reilly";
$ser=serialize($string);    # safe -- won't count the slash
$result=addslashes($ser);
?>

...and not this...

<?php
$string
="O'Reilly";
$add=addslashes($string);  # RISKY!  -- will count the slash
$result=serialize($add);
?>

In both cases, a backslash will be added after the apostrophe in "O'Reilly"; only in the second case will the backslash be included in the string length as recorded by serialize().

[Note to the maintainers: You may, at your option, want to link this note to serialize() as well as to addslashes().  I'll refrain from doing such cross-posting myself...]
php at slamb dot org
30-Oct-2002 01:48
spamdunk at home dot com, your way is dangerous on PostgreSQL (and presumably MySQL). You're quite correct that ANSI SQL specifies using ' to escape, but those databases also support \ for escaping (in violation of the standard, I think). Which means that if they pass in a string that includes a "\'", you expand it to "\'''" (an escaped quote followed by a non-escaped quote. WRONG! Attackers can execute arbitrary SQL to drop your tables, make themselves administrators, whatever they want.)

The best way to be safe and correct is to:

- don't use magic quotes; this approach is bad. For starters, that's making the assumption that you will be using your input in a database query, which is arbitrary. (Why not escape all "<"s with "&lt;"s instead? Cross-site scripting attacks are quite common as well.) It's better to set up a way that does whatever escaping is correct for you when you use it, as below:

- when inserting into the database, use prepared statements with placeholders. For example, when using PEAR DB:

<?php
   $stmt
= $dbh->prepare('update mb_users set password = ? where username = ?');
  
$dbh->execute($stmt, array('12345', 'bob'));
?>

Notice that there are no quotes around the ?s. It handles that for you automatically. It's guaranteed to be safe for your database. (Just ' on oracle, \ and ' on PostgreSQL, but you don't even have to think about it.)

Plus, if the database supports prepared statements (the soon-to-be-released PostgreSQL 7.3, Oracle, etc), several executes on the same prepare can be faster, since it can reuse the same query plan. If it doesn't (MySQL, etc), this way falls back to quoting code that's specifically written for your database, avoiding the problem I mentioned above.

(Pardon my syntax if it's off. I'm not really a PHP programmer; this is something I know from similar things in Java, Perl, PL/SQL, Python, Visual Basic, etc.)
guy_AT_datalink_DOT_net_DOT_au
30-Mar-2002 04:58
If you're trying to escape quotes in a javascript event as such:

<img src="foo.gif" OnMouseOver="alert('<? print $myString ?>')">

It helps to perform this first:

$myString = str_replace("'", "\'", $myString);
$myString = str_replace('"', "'+String.fromCharCode(34)+'", $myString);
phpman at priorwebsites.com
19-Mar-2002 08:02
You MySQL folks might also want to check out mysql_escape_string().

--------- copied from mysql_escape_string():
If you're wondering what's the difference between mysql_escape_string() and
AddSlashes(), I found this from looking at the source code of MySQL
3.23.32 and PHP 4.0.6:

- mysql_escape_string calls MySQL's library function of the same name,
which prepends slashes to the following characters: NUL (\x00), \n, \r, \,
', " and \x1a.

- AddSlashes escapes NUL, ', " and \.

While mysql_escape_string seems safer, my experience shows that escaping
strings with AddSlashes (which is also done automatically if
magic_quotes_gpc is on) is sufficient, so it seems you can pick whichever
you wish.
hybrid at n0spam dot pearlmagik dot com
09-May-2001 01:46
Remember to slash underscores (_) and percent signs (%), too, if you're going use the LIKE operator on the variable or you'll get some unexpected results.
php at NO_SPAMj-w3 dot com
02-Apr-2001 06:18
As mentioned, magic_quotes_gpc automatically adds slashes to POST and GET data and these slashes don't go in the database.  BUT, be careful of this. If you have a form with an error check, make sure you strip the slashes if your form remembers the OK fields, so the user doesn't view these automagically added slashes.
spamdunk at home dot com
06-Mar-2001 04:12
FYI, Quoting the single quote (') as ('') is not an Oracle stle, or a Sybase style, or any other vendor-specific style. It is the ANSI SQL (i.e. SQL standard) style.

Using blackslahes to escape characters is a proprietary extension that some databases have. If you want your SQL to be portable across databases, don't use it.

For example (on PostgreSQL):

=> create table t (s varchar(64));
CREATE
=> insert into t values ('one''two"three''');
INSERT 206474 1
wapkey=> select * from t;
       s
----------------
 one'two"three'
(1 row)

... as expected, as per the standard.
nightowl at uk2 dot net
12-Dec-2000 12:31
If you want to import the exported file into Access, you also need to dubble the "'s .

I used

$write = ereg_replace("\"","\"\"",$original_text);
bruce dot j dot cadiz at boeing dot com
20-Nov-1999 12:22
In ref. to note stating
"Using an oracle database addslashes doesn`t work to escape single quotes."<BR>
This is not successful when passed to ora_parse():<br>
http://www.php.net/manual/function.ora-parse.php3<p> Another way to deal with this problem is to use stripslashes():
<br>
http://www.php.net/manual/function.stripslashes.php3
<br>function. PHP will try to "escape" single quotes on name
value pairs (POST or GET) <P>example: A query string is passed with single quotes like<BR>
(SELECT * FROM EMP WHERE EMPNAME = 'SMITH')<BR><BR>
will be changed to<BR>
(SELECT * FROM EMP WHERE EMPNAME =\'SMITH\')<BR><BR>
stripslashes():<br>
http://www.php.net/manual/function.stripslashes.php3
<br> will fix this.
<BR>(ora_parse($curs,stripslashes($query)));

<addcslashesbin2hex>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 18:35:34 2005 EDT