从网站在主机服务器上创建文本文件

时间:2018-05-25 17:05:13

标签: javascript java php server user-input

我试图让用户能够将文本文件写入网站主机服务器上的目录。用例如下:

  1. 用户访问www.example.com/createtext
  2. 用户在文本框中键入他们想要保存的内容,例如“Hello”,
  3. 托管网站的服务器会在其中一个目录中创建一个文本文件。
  4. 在服务器上,现在有一个文本文件在C:/ somedirectory / dailytexts /中写有“Hello”
  5. 我目前编写了一个简单的页面,其中包含一个表单,该表单将接收文本信息并将其保存到文本文件中,其名称为当前日期。

    <script language="Javascript">
        var time = new Date();
        var formattedTime = time.toLocaleTimeString();
    
        function download(filename, text) {
          var pom = document.createElement('a');
          pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    
        encodeURIComponent(text));
          pom.setAttribute('download', formattedTime);
    
          pom.style.display = 'none';
          document.body.appendChild(pom);
    
          pom.click();
          document.body.removeChild(pom);
        }
    </script>
    
    <form id="form" class="topBefore" onsubmit="download(this['name'].value, this['text'].value)">
        <textarea id="message" type="text" placeholder="Hello" name="text"></textarea>
        <input id="submit" type="submit" value="Download Text File">
    </form>
    

    这只是将文本文件下载到用户的计算机上。相反,我希望在主机上创建该文件。

    有没有这样做?特别是,只使用JavaScript或Java。但是,如果必须使用像PHP这样的东西,那么它也会起作用。

1 个答案:

答案 0 :(得分:0)

AFAIK,浏览器中的JS只允许你做客户端而不修改服务器内容而不使用...(例如)服务器端的PHP脚本。

此解决方案(现在)仅使用HTML和PHP,需要消除JS。

HTML (已修改)

<form id="form" class="topBefore" action="createtext.php" method="GET">
<textarea id="message" type="text" placeholder="Hello" name="name"></textarea>
<textarea id="message2" type="text" placeholder="Hello" name="text"></textarea>
<input id="submit" type="submit" value="Download Text File">

PHP:(名为 createtxt.php 的文件)

if(isset($_GET['name']) && isset($_GET['text']))  {
    $filename = preg_replace('#[^A-Za-z0-9_-]#', '', $_GET['name']);
    $file = $_SERVER['DOCUMENT_ROOT']."/textfiles/$filename.txt";
    $f = fopen($file, 'w');
    fwrite($f, $_GET['text']);
    fclose($f);
    echo 'Success.';
}  else  {
    echo 'Error.';
}

文件创建需要两个参数 - 文件名和内容,而问题的HTML中只提供了一个textarea。现在包含另一个文件名。 jQuery / JS被删除了。相反,表单现在将数据发送到createtext.php,后者创建文件(fopen),写入文本(fwrite)并回显“成功”。 - 请注意两件事:

  1. 我们将文本文件保存到与textfiles相同的目录中名为createtext.php的文件夹中。该文件夹必须存在于之前 - 它不会自动创建,如果不存在,PHP将抛出错误。
  2. 您可以将echo 'Success.';替换为其他操作:例如重定向到其他页面或同一页面(header),或echo ing / readfile - HTML页面