ConFoo Montreal 2026: Call for Papers

Voting

: min(nine, nine)?
(Example: nine)

The Note You're Voting On

divinity76 at gmail dot com
3 years ago
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.

<< Back to user notes page

To Top