简体   繁体   中英

PHP how to prevent PHP from escaping html fopen fwrite

I am trying to make an app that will allow me to more easly create HTML documents.

It mostly works except that when I write to the file it adds backslashes.

<a href=\"google.com\">google</a>

Any idea how to stop it from doing this?

I got it to work! if i stripslashes() before I write it to the file it will save/create the file with out the \\ Thank you for all of your help!

It is probably because the magic quotes are on, if you don't want to use the stripslashes every time, you should disable them either in your php.ini file or with an htaccess file like such:

In php.ini file:

magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off

OR in .htaccess file:

php_flag magic_quotes_gpc Off

OR disable them directly in your code:

if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}

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

If you are using a single-quoted string, you shouldn't use escape double-quotes with backslashes, as they are interpreted literally.

From the docs :

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

this behaviour is caused by PHP's deprecated Magic Quotes directive, yours is still activated, as it is by default in any default PHP install prior to 5.4. Unless you specify a length argument, fwrite will look at magic-quotes-runtime to see wether it'll escape or not.

to turn it off you could place

php_flag magic_quotes_gpc Off

in a .htaccess file, you'll need to use apache DSO to allow for this option

or you can disable it in php.ini

if you can't do either of these things because you're on a shared host or for another reason, then solve it in code.

function write($resource,$string,$length)
    if (get_magic_quotes_gpc()) {
        $string = stripslashes($string);

    }
    return fwrite($resource, $string,$length);
}

I had a similar problem but with a $_POST['body'] variable. This works for me:

str_replace("\\", "", $_POST['body']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM