且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP使用fwrite()自动转义报价

更新时间:2023-12-04 12:53:04

它不是fwrite这样做,因为你有 magic_quotes 启用。



如果您不能在php.ini文件中禁用魔术引号,那么您可以在运行时禁用它,一点点PHP循环遍历所有的输入数组,并删除不必要的斜杠,那么您不需要担心要剥离哪个POST / GET键。 禁用魔术报价

 <?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');
}
?>


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?

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');
}
?>