PHP Escaping Quotes Automatically When Using fwrite()

左心房为你撑大大i 提交于 2019-11-28 11:02:00

问题


PHP is automatically escaping my quotes before writing to a file using fwrite. I am trying to make a test code page. Here is the code I have:

<?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>
";
}
?>

When I enter the following into my form:

<?php
echo 'test';
?>

It gets saved in the file as:

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

Why is php automatically escaping my quotes?


回答1:


Its not fwrite thats doing it, its because you have magic_quotes enabled.

If you cant disable magic quotes in your php.ini file then you can disable it at runtime, a simple bit of PHP will loop through ALL your input arrays and strip out the unwanted slashes, then you wont need to worry about which POST/GET keys to strip. 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:


It's not fwrite, its $_POST

With these knowledge please find you answer here:

  • Why are $_POST variables getting escaped in PHP?

So what you have to do is just small fix:

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



回答3:


http://php.net/manual/en/security.magicquotes.php

http://www.php.net/manual/en/security.magicquotes.disabling.php




回答4:


You have magic quotes enabled. Disable them in your php.ini file (magic_quotes_gpc=off) or pass your $_POST['code'] through stripslashes.



来源:https://stackoverflow.com/questions/10440698/php-escaping-quotes-automatically-when-using-fwrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!