Home  >  Article  >  Backend Development  >  PHP returns the function addslashes() that adds a backslash before a predefined character

PHP returns the function addslashes() that adds a backslash before a predefined character

黄舟
黄舟Original
2017-11-02 09:45:442145browse

Example

Add a backslash before each double quote ("):

<?php 
$str = addslashes(&#39;What does "yolo" mean?&#39;);
echo($str); 
?>

Definition and usage

addslashes() function returns the predefined characters Strings preceded by a backslash:

Single quotation mark (')

Double quotation mark (")

Backslash. Bar (\)

NULL

Tip: This function can be used to prepare appropriate strings for strings stored in the database and database query statements.

Note: By default, the PHP instruction magic_quotes_gpc is on, automatically running addslashes() for all GET, POST and COOKIE data. Do not use addslashes() on strings that have been escaped by magic_quotes_gpc, as this will result in double escaping. When encountering this situation, you can

use the function

get_magic_quotes_gpc() for detection. Syntax

addslashes(string)

ParametersstringTechnical details
Description
Required. Specifies the string to be escaped.

Return value: PHP version:

更多实例

向字符串中的预定义字符添加反斜杠:

<?php
$str = "Who&#39;s Peter Griffin?";
echo $str . " This is not safe in a database query.<br>";
echo addslashes($str) . " This is safe in a database query.";
?>

php addslashes函数的作用是在预定义的字符前面加上反斜杠,这些预定义字符包括:

单引号(')

双引号(")

反斜杠(\)

NULL

addslashes函数经常使用在向数据库插入数据时,比如有一个字符串

$str="my name&#39;s wxp";

现在要将这个字符串插入到数据库表中,由于该字符串有单引号',这样很可能与mysql拼接字符串的单引号'冲突,导致SQL语句不正确,也就无法正常执行插入操作,此时我们需要使用addslashes函数处理这个字符串。如:

$str="my name&#39;s wxp";echo addslashes($str);//输出my name\'s wxp

然后在拼接mysql字符串:

$sql="insert into student(student_name)values(&#39;".addslashes($str)."&#39;)";
mysql_query($sql);

此时字符串被插入到数据库,那么大家是否知道插入的字符串是带反斜杠还是不带反斜杠呢?恐怕很多人都会认为肯定是带反斜杠的字符串。其实这个答案是错误的,插入的字符串是没有带反斜杠。至于为什么插入的字符串在数据库中是没有加反斜杠,请大家继续看下面讲解。

如果字符串$str="my name's wxp"是使用POST和GET提交的数据,这个时候插入数据库中的数据是带反斜杠的,由此可知addslashes只是在POST和GET数据插入数据库时才会把反斜杠同时插入到数据库,其他情况下不会将反斜杠插入到数据库。

Returns the escaped string.
4+

The above is the detailed content of PHP returns the function addslashes() that adds a backslash before a predefined character. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn