百科狗-知识改变命运!
--

addslashes() - 使用反斜线引用字符串 - php 字符串函数

梵高1年前 (2023-11-21)阅读数 17#技术干货
文章标签字符串

addslashes()

addslashes() - 使用反斜线引用字符串 - php 字符串函数

(PHP 4, PHP 5, PHP 7)

使用反斜线引用字符串

说明

addslashes(string $str) : string

返回字符串,该字符串为了数据库查询语句等的需要在某些字符前加上了反斜线。这些字符是单引号(')、双引号(")、反斜线()与 NUL(NULL字符)。

一个使用addslashes()的例子是当你要往数据库中输入数据时。例如,将名字O'reilly插入到数据库中,这就需要对其进行转义。强烈建议使用 DBMS 指定的转义函数(比如 MySQL 是mysqli_real_escape_string(),PostgreSQL 是pg_escape_string()),但是如果你使用的 DBMS 没有一个转义函数,并且使用来转义特殊字符,你可以使用这个函数。仅仅是为了获取插入数据库的数据,额外的并不会插入。当 PHP 指令magic_quotes_sybase被设置成on时,意味着插入'时将使用'进行转义。

PHP 5.4 之前 PHP 指令magic_quotes_gpc默认是on,实际上所有的 GET、POST 和 COOKIE 数据都用被addslashes()了。不要对已经被magic_quotes_gpc转义过的字符串使用addslashes(),因为这样会导致双层转义。遇到这种情况时可以使用函数get_magic_quotes_gpc()进行检测。

参数

$str

要转义的字符。

返回值

返回转义后的字符。

范例

一个addslashes()例子

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.)
In addition to the post made by Aditya P Bhatt below. This code works fine for posting a single string but does not work for posting arrays.
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.
May it is better use the function mysql_real_escape_string instead of addslashes when inserting data into a MySQL database. Check it at:
http://www.php.net/manual/en/function.mysql-real-escape-string.php
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 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.
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.
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.
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
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.

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!
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
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.
If you have problems with adding images or other binady data with addslashes() for php 4.3 >= use:

and put in your SQL field='$chrData' ! please remark quotes
For PHP 7.3.* use FILTER_SANITIZE_ADD_SLASHES.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)