我用这个作为引用: Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?
我可以使用 JAVASCRIPT/jQuery 将表单中的输入保存到 HTML 中的 .txt 中,然后使用它吗?但这是针对客户端的,我想要服务器端。
我有一个包含以下内容的 TXT 文件:
PAGE=1
until [ $PAGE -gt 9 ]; do
wget "http://www.example.com/INPUT-WORD-HERE/page_0"$PAGE".jpg"
let PAGE+=1
done
PAGE=10
until [ $PAGE -gt 99 ]; do
wget "http://www.example.com/INPUT-WORD-HERE/page_"$PAGE".jpg"
let PAGE+=1
done
我是否可以从 HTML 表单中读取输入并将其保存在此 TXT 文件(托管)中的特定位置。具体位置是INPUT-WORD-HERE。因此,我们的想法是将所有 INPUT-WORD-HERE 替换为 HTML 输入。
最佳答案
因此,根据您的描述,这就是应该做的事情(当您用 PHP 标记您的问题时,我使用了 PHP 代码):
以字符串形式打开批处理文件。
$fileTXT = file_get_contents($path_to_your_file, FILE_USE_INCLUDE_PATH);
(将
$path_to_your_file
替换为您要更新的文件的相对路径)将 INPUT-WORD-HERE 的所有实例替换为新输入:
$fileTXT = str_replace("INPUT-WORD-HERE", $textToReplace, $fileTXT);
但事情并没有那么简单。这比一开始看起来有点棘手,因为 INPUT-WORD-HERE 每次都不会是相同的文本。我们需要创建一个通用脚本来替换任何值:
$pos1 = strpos($fileTXT, "http://www.example.com/"); $textFrom = substr($fileTXT, $pos1+23, strpos($fileTXT, "/", $pos1 + 23) - $pos1 - 23); $fileTXT = str_replace("http://www.example.com/" . $textFrom . "/", "http://www.example.com/" . $textTo . "/", $fileTXT);
我替换整个 URL,以避免如果先前的 INPUT-WORD-HERE 值与文件中的不同文本匹配(例如:“example”或“PAGE”)可能出现的问题
保存文件。
file_put_contents($path_to_your_file, $fileTXT);
最终的代码如下:
<?php
// here the relative path to your batch file
$filename = "myfile.txt";
// replace $_GET["txt"] for the name of the input that will have the new value. You can use $_POST too
$textTo = $_GET["txt"];
// read the content of the file into a string
$fileTXT = file_get_contents($filename, FILE_USE_INCLUDE_PATH);
// get the word to be replace from the URL (23 is the length of "http://www.example.com/", you'll need to change that number to fit the URL that you place there)
$pos1 = strpos($fileTXT, "http://www.example.com/");
$textFrom = substr($fileTXT, $pos1+23, strpos($fileTXT, "/", $pos1 + 23) - $pos1 - 23);
$fileTXT = str_replace("http://www.example.com/" . $textFrom . "/", "http://www.example.com/" . $textTo . "/", $fileTXT);
// overwrite the content of the file
file_put_contents($filename, $fileTXT);
正如我在评论中指出的,这个解决方案存在一些危险,不应该与普通用户一起使用(你说这是好的,因为它只适合你)。如果您更改它以便普通用户可以访问它,您应该对输入进行预处理和清理。
<小时/>根据用户的要求,这是 HTML 表单的简单示例:
<form method="get" action="YOUR_PHP_FILE_WITH_THE_ABOVE_CODE">
<label for="txt">
Write here the new name:
<input type="text" name="txt" id="txt" />
</label>
<input type="submit" value="Make Changes" />
</form>
您只需确保文本输入与您在$_GET
(或在$_POST
)中读取的参数具有相同的名称,然后您需要将表单更改为 method="post"
)。
关于javascript - 我可以从 HTML 表单中读取输入并将其保存在 TXT 文件中的特定位置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30013751/