PHP使用fwrite()时自动转义引号

时间:2012-05-03 23:21:59

标签: php file escaping quotes fwrite

在使用fwrite写入文件之前,PHP会自动转义我的引号。我正在尝试制作一个测试代码页。这是我的代码:

<?php
if ($_GET['test'] == 'true') {
$code = $_POST['code'];
$file = fopen('testcode.inc.php', 'w+');
fwrite($file, $code);
fclose($file);
require_once('testcode.inc.php');
}
else {
echo "
<form method='post' action='testcode.php?test=true'>
<textarea name='code' id='code'></textarea><br><br>
<button type='submit'>Test!</button><br>
</form>
";
}
?>

当我在表单中输入以下内容时:

<?php
echo 'test';
?>

它将保存在文件中:

<?php
echo \'test\';
?>

为什么php会自动转义我的引号?

4 个答案:

答案 0 :(得分:2)

不是 fwrite ,其 $ _ POST

有了这些知识,请在这里找到答案:

所以你要做的只是小修补:

if (get_magic_quotes_gpc()) {
  $code = stripslashes($_POST['code']);
}else{
  $code = $_POST['code'];
}

答案 1 :(得分:1)

它不是fwrite那样做,因为你启用了magic_quotes

如果您无法在php.ini文件中禁用魔术引号,那么您可以在运行时禁用它,一小段PHP将遍历所有输入数组并删除不需要的斜杠,然后您不必担心哪个剥离的POST / GET键。 Disabling Magic Quotes

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_gpc(&$value)
    {
        $value = stripslashes($value);
    }
    array_walk_recursive($_GET, 'stripslashes_gpc');
    array_walk_recursive($_POST, 'stripslashes_gpc');
    array_walk_recursive($_COOKIE, 'stripslashes_gpc');
    array_walk_recursive($_REQUEST, 'stripslashes_gpc');
}
?>

答案 2 :(得分:1)

答案 3 :(得分:0)

您启用了魔术引号。在php.ini文件(magic_quotes_gpc=off)中停用它们,或将$_POST['code']传递给stripslashes