简体   繁体   English

php file_put_contents()用空格替换'+'

[英]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. 我正在尝试使用php函数file_put_contents()和ajax覆盖文件,但是在写入文件时加号(+)替换为空格。 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. 基本上我在这里尝试做的是允许用户使用内联编辑器来更改文本,然后获取更新的DOM并将其写回文件,覆盖以前的内容。

Here is overwrite.php 这是overwrite.php

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

There are two things going wrong with this actually 实际上有两件事情出了问题

1). 1)。 the + symbol is being replace with a space (solved thanks to simultaneous answers by @deceze @Justinas) +符号正在替换为空格(由@deceze @Justinas同时回答解决)

2). 2)。 there are style tags being added inside the head tag (still unsolved and mighty annoying) 在head标签内添加了样式标签(仍未解决并且很烦人)

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

+ in the x-www-form-urlencoded format means space! + x-www-form-urlencoded格式 意味着空间! You need to correctly url-encode your content before sending it to the server: 在将内容发送到服务器之前,您需要对内容进行正确的url编码:

xhttp.send("html=" + encodeURIComponent(html.outerHTML));  
  1. You are sending plain text via GET . 您正通过GET发送纯文本。 In URL + means space so when PHP reads URL string it automatically url-decodes it and your + is replaced with space. 在URL +表示空格,因此当PHP读取URL字符串时,它会自动对其进行URL解码,并且您的+将替换为空格。 Use xhttp.send('html='+encodeURIComponent(html.outerHTML)) . 使用xhttp.send('html='+encodeURIComponent(html.outerHTML))

  2. Are you using any framework or any other automated system to auto-append styles? 您是否使用任何框架或任何其他自动系统来自动添加样式?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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