开发者

search string with preg_replace

$html = file_get_contents("1.html");
eval("print \"" . addcslashes(preg_replace("/(---(.+?)---)/", "\\2", $html), '"') . "\";");

This searches an string and replaces开发者_Go百科 ---$variable--- with $variable.

How can I rewrite the script so that it searches for ---$_SESSION['variable']--- and replaces with $_SESSION['variable']?


You could just change the replacement to:

preg_replace("/(---\\\$_SESSION\\['(.+?)'\\]---)/", "\${\$_SESSION['\\2']}", $html)

but I wouldn't at all recommend it. As always, eval is a big clue you're doing something wrong.

Non-templating uses of $ in 1.html or the session variable will cause errors. Arbitrary code in 1.html or the session variable can be executed via the ${...} syntax, potentially compromising your server. Less-than signs or ampersands in the session variable will be output as-is, leading to cross-site-scripting attacks.

A better strategy is to keep the string as just a string, not a PHP command. Find the ---...--- sections and replace those separately:

$parts= preg_split('/---(.+?)---/', $html, null, PREG_SPLIT_DELIM_CAPTURE);
for ($i= 1; $i<count($parts); $i+= 2) {
    $part= trim($parts[$i]);
    if (strpos($part, "\$_SESSION['")==0) {
        $key= stripcslashes(substr($part, 11, -2));
        $parts[$i]= htmlspecialchars($_SESSION[$key], ENT_QUOTES);
    }
}
$html= implode('', $parts);

(Not tested, but should be along the right lines. You may not want htmlspecialchars if you really want your variables to contain active HTML; this is not usually the case.)


The function you need is preg_quote(). But before I post any code here: Are you really really really sure your $html or your $_SESSION['variable'] contains no malicious strings like $(cat /etc/passwd)? If you are, double-check. If you still are, go ahead using this:

preg_replace("/(---" . preg_quote($_SESSION['variable'], '/') . "---)/", "\\2", $html)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜