php file_put_contents()用空格

时间:2015-11-16 09:29:58

标签: php html ajax

我正在尝试使用php函数file_put_contents()和ajax覆盖文件,但是在写入文件时加号(+)替换为空格。这是代码段

<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>

基本上我在这里要做的是允许用户使用内联编辑器来更改文本,然后获取更新的DOM并将其写回文件,覆盖以前的内容。

以下是overwrite.php

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

这实际上有两个问题

1)。 +符号正在替换为空格(由@deceze @Justinas同时回答解决)

2)。在head标签内部添加了样式标签(仍未解决并且非常烦人)

很高兴找到这里发生的事情,也许我可以改变代码来解决它。

我很清楚允许用户修改内容然后将其直接写入文件的安全风险,我只是在这里进行实验。

感谢

2 个答案:

答案 0 :(得分:2)

x-www-form-urlencoded format 中的

+表示空间!在将内容发送到服务器之前,您需要对内容进行正确的URL编码:

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

答案 1 :(得分:1)

  1. 您要通过GET发送纯文字。在URL +中表示空格,因此当PHP读取URL字符串时,它会自动对其进行url解码,并将+替换为空格。使用xhttp.send('html='+encodeURIComponent(html.outerHTML))

  2. 您是否使用任何框架或任何其他自动系统来自动添加样式?