1

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?

Ethan H
  • 717
  • 1
  • 13
  • 27

4 Answers4

2

It's not fwrite, its $_POST

With these knowledge please find you answer here:

So what you have to do is just small fix:

if (get_magic_quotes_gpc()) {
  $code = stripslashes($_POST['code']);
}else{
  $code = $_POST['code'];
}
Community
  • 1
  • 1
Peter
  • 16,453
  • 8
  • 51
  • 77
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');
}
?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

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

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592