pinch boi triggered af
pinch boi triggered af

Reputation: 544

php file_put_contents() replaces '+' with space

I'm trying to overwrite a file using php function file_put_contents() along with ajax, how ever while writing to the file the plus sign (+) is replace with a space. Here is the code snippet

<html>
    <head></head>
    <body>
        <div>inline editor will change this text</div>
        <button type="button" onclick="loadDoc()">save changes</button>
    <script>
        function loadDoc() {
            var html = document.getElementsByTagName('html')[0];
            var xhttp = new XMLHttpRequest();
            xhttp.open("POST", "overwrite.php", true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send("html="+html.outerHTML);  
            <!--the + here is replace with a space-->
        }
    </script>
    </body>
</html>

Basically what i'm trying to do here is to allow the user to use inline editors to change the text and then get the updated DOM and write it back to the file, overwriting the previous content.

Here is overwrite.php

<?php
    $var = $_POST['html'];
    file_put_contents("index.php", $var );
?>

There are two things going wrong with this actually

1). the + symbol is being replace with a space (solved thanks to simultaneous answers by @deceze @Justinas)

2). there are style tags being added inside the head tag (still unsolved and mighty annoying)

it would be great to find out what is actually happening here, and maybe i could alter the code to fix it.

I'm well aware of the security risks of allowing users to modify content and then writing it directly to a file, i'm just experimenting here.

thanks

Upvotes: 1

Views: 356

Answers (2)

Justinas
Justinas

Reputation: 43507

  1. You are sending plain text via GET. In URL + means space so when PHP reads URL string it automatically url-decodes it and your + is replaced with space. Use xhttp.send('html='+encodeURIComponent(html.outerHTML)).

  2. Are you using any framework or any other automated system to auto-append styles?

Upvotes: 1

deceze
deceze

Reputation: 522500

+ in the x-www-form-urlencoded format means space! You need to correctly url-encode your content before sending it to the server:

xhttp.send("html=" + encodeURIComponent(html.outerHTML));  

Upvotes: 2

Related Questions