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
function xpath_quote(string $value):string{
if(false===strpos($value,'"')){
return '"'.$value.'"';
}
if(false===strpos($value,'\'')){
return '\''.$value.'\'';
}
$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
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'); $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); if ($string === '' || ctype_digit($string)) {
return $string;
}
$result = preg_replace_callback('/[^a-z0-9]/iSu', $cssMatcher, $string);
return mb_convert_encoding($result, $originalEncoding, 'UTF-8'); }
?>
- but never addslashes.