2015-05-03 45 views
0

我以此爲參考: Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?我可以從HTML表單讀取輸入並將其保存在TXT文件中的特定位置嗎?

可以保存輸入從形式HTML爲.txt,使用Javascript/jQuery的,然後使用它?但是這是針對客戶端,我想要服務器端。

我有此內容的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。所以,這個想法是用HTML輸入替換所有的INPUT-WORD-HERE。

+0

JavaScript不允許將文件讀寫到客戶端計算機。如果你想在服務器上存儲數據,你可以使用服務器端語言,如PHP,Node.js或ASP.NET –

+0

這個txt文件位於客戶端計算機上嗎? –

+0

我將txt文件存儲在服務器中以供稍後使用。 –

回答

1

因此,從你的描述,這是應該做的(我用PHP的代碼,你標記它你的問題):

  1. 打開批處理文件作爲一個字符串。

    $fileTXT = file_get_contents($path_to_your_file, FILE_USE_INCLUDE_PATH); 
    

    (更換$path_to_your_file一起,你要更新的文件的相對路徑)

  2. 更換輸入 - 字在這裏與新輸入的所有實例:

    $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); 
    

    我更換整個網址,以避免可能出現的問題,如果先前輸入-WORD-HERE值相匹配的文件在不同的文本(例如:「example」或「PAGE」)

  3. 保存文件。

    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")中閱讀。

+0

感謝您的回答Alvaro Montoro先生。 –

+0

我有困難製作表格,你可以添加模型輸入表單嗎?謝謝 –

+0

我添加了一個可以與PHP一起工作的小例子 –

相關問題