Related Examples ( Source code ) » addslashes

Code Examples / Notes » addslashes

mike

[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;
}
?>

adrian c

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

yoder2

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.

picky

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.

sam dot fullman

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..

lancelight

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 :/

php

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.)

hybrid

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.

gv

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.

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!

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.

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.

david harris

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 . '\'';

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.

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.

steve

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.

hoskerr

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...]

percy

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!

php

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.

unsafed

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.