PHP.mk документација

addslashes

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.addslashes.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.addslashes.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
addslashes

Референца за `function.addslashes.php` со подобрена типографија и навигација.

function.addslashes.php

addslashes

(PHP 4, PHP 5, PHP 7, PHP 8)

addslashesЦитат на стринг со коси црти

= NULL

addslashes(string $string): string

Враќа стринг со додадени коси црти пред знаците што треба да се избегнат. Овие знаци се:

  • единечен наводник (')
  • двоен наводник (")
  • коса црта (\)
  • NUL (NUL бајт)

Случај на употреба на addslashes() е избегнување на гореспоменатите знаци во стринг што треба да се процесира од PHP:

Пример #1 Избегнување на знаци

<?php
$str
= "O'Reilly?";
eval(
"echo '" . addslashes($str) . "';");
?>

На addslashes() понекогаш погрешно се користи за да се обиде да се спречи SQL инјекција. Наместо тоа, треба да се користат функции за избегнување специфични за базата на податоци и/или подготвени изјави.

Параметри

string

Стрингот што треба да се избегне.

Вратени вредности

Враќа избегнатиот стринг.

Примери

Пример #2 А addslashes() example

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

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

Види Исто така

  • stripcslashes() - Де-цитирање на стринг со addcslashes
  • stripslashes() - Отстранува наводници од цитиран стринг
  • addcslashes() - Цитирање на стринг со коси црти во C стил
  • htmlspecialchars() - Конвертирај специјални знаци во HTML ентитети
  • quotemeta() - Цитирање на мета знаци
  • get_magic_quotes_gpc() Ја добива моменталната активна конфигурациска поставка на magic_quotes_runtime

Белешки од корисници Управување со PDO конекции

roysimke на microsoftsfirstmailprovider dot com
пред 15 години
Never use addslashes function to escape values you are going to send to mysql. use mysql_real_escape_string or pg_escape at least if you are not using prepared queries yet.

keep in mind that single quote is not the only special character that can break your sql query. and quotes are the only thing which addslashes care.
[email protected]
пред 4 години
Addslashes is *never* the right answer, it's (ab)use can lead to security exploits!

if you need to escape HTML, it's (unfortunately)
<?php
echo htmlentities($html, ENT_QUOTES|ENT_SUBSTITUTE|ENT_DISALLOWED);
?>
if you need to quote shell arguments, it's
<?php
$cmd.= " --file=" . escapeshellarg($arg);
?>
if you need to quote SQL strings it's
<?php
$sql.= "WHERE col = '".$mysqli->real_escape_string($str)."'";
?>
or
<?php
$sql.= "WHERE col = " . $pdo->quote($str);
?>
if you need to quote javascript/json strings its
<?php
let str = <?=json_encode($str, JSON_THROW_ON_ERROR);?>;
?>

if you need to quote a string in xpath it's
<?php
//based on https://stackoverflow.com/a/1352556/1067003
function xpath_quote(string $value):string{
    if(false===strpos($value,'"')){
        return '"'.$value.'"';
    }
    if(false===strpos($value,'\'')){
        return '\''.$value.'\'';
    }
    // if the value contains both single and double quotes, construct an
    // expression that concatenates all non-double-quote substrings with
    // the quotes, e.g.:
    //
    //    concat("'foo'", '"', "bar")
    $sb='concat(';
    $substrings=explode('"',$value);
    for($i=0;$i<count($substrings);++$i){
        $needComma=($i>0);
        if($substrings[$i]!==''){
            if($i>0){
                $sb.=', ';
            }
            $sb.='"'.$substrings[$i].'"';
            $needComma=true;
        }
        if($i < (count($substrings) -1)){
            if($needComma){
                $sb.=', ';
            }
            $sb.="'\"'";
        }
    }
    $sb.=')';
    return $sb;
}
$xp->query('/catalog/items/item[title='.xpath_quote($var).']');
?>
if you need to quote strings in CSS its
<?php
// CSS escape code ripped from Zend Framework ( https://github.com/zendframework/zf2/blob/master/library/Zend/Escaper/Escaper.php )
function css_escape_string($string)
{
    $cssMatcher = function ($matches) {
        $chr = $matches[0];
        if (strlen($chr) == 1) {
            $ord = ord($chr);
        } else {
            $chr = mb_convert_encoding($chr, 'UTF-16BE', 'UTF-8'); // $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8');
            $ord = hexdec(bin2hex($chr));
        }
        return sprintf('\\%X ', $ord);
    };
    $originalEncoding = mb_detect_encoding($string);
    if ($originalEncoding === false) {
        $originalEncoding = 'UTF-8';
    }
    ;
    $string = mb_convert_encoding($string, 'UTF-8', $originalEncoding); // $this->toUtf8($string);
                                                                        // throw new Exception('mb_convert_encoding(\''.$string.'\',\'UTF-8\',\''.$originalEncoding.'\');');
    if ($string === '' || ctype_digit($string)) {
        return $string;
    }
    $result = preg_replace_callback('/[^a-z0-9]/iSu', /*$this->*/$cssMatcher, $string);
    // var_dump($result);
    return mb_convert_encoding($result, $originalEncoding, 'UTF-8'); // $this->fromUtf8($result);
}

?>

- but never addslashes.
svenr на selfhtml точка org
пред 15 години
To output a PHP variable to Javascript, use json_encode().

<?php

$var = "He said \"Hello O'Reilly\" & disappeared.\nNext line...";
echo "alert(".json_encode($var).");\n";

?>

Output:
alert("He said \"Hello O'Reilly\" & disappeared.\nNext line...") ;
hoskerr на nukote dot com
пред 23 години
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...]
unsafed
20 години пред
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.
powtac at gmx dot de
12 години пред
If all you want to do is quote a string as you would normally do in PHP (for example, when returning an Ajax result, inside a json string value, or when building a URL with args), don't use addslashes (you don't want both " and ' escaped at the same time). Instead, just use this function:

<?php
function Quote($Str) // Double-quoting only
    {
    $Str=str_replace('"','\"',$Str);
    return '"'.$Str.'"';
    } // Quote
?>

Modify this easily to get a single-quoting function.
stuart на horuskol dot co dot uk
пред 17 години
Be careful on whether you use double or single quotes when creating the string to be escaped:

$test = 'This is one line\r\nand this is another\r\nand this line has\ta tab';

echo $test;
echo "\r\n\r\n";
echo addslashes($test);

$test = "This is one line\r\nand this is another\r\nand this line has\ta tab";

echo $test;
echo "\r\n\r\n";
echo addslashes($test);
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.