簡體   English   中英

使用PHP從表單輸入更新HTML文件

[英]Updating HTML files using PHP from form input

基本上,我想使用用戶從標准格式輸入的代碼段更新靜態HTML文件。 我了解更新文件的工作方式,但不確定如何將代碼輸入從表單輸入到我的php文件中,如下所示。

<?php
if($handle = opendir()) {
$search = '</body>';
replace = <<< EOF
<!-- I want to populate this with form field input.-->
EOF;
while(false !== ($entry = readdir($handle))) {
    if(is_dir($entry)) continue; 

    $content = file_get_contents($entry); 
    $content = str_replace($search, $replace . '</body>', $content); 
    file_put_contents($entry, $content); 
}
}

echo 'done';

?>

任何幫助,不勝感激。

我會對此有所不同。 我建議除了要修改的模板文件外,還要有一個模板文件。 這樣,您總是在修改新副本,而不必擔心新版本中的更改。

如果您的需求變得更加高級,而不僅僅是添加一些標記,那么我建議您使用DOM解析器。

最后,我確定您有充分的理由來編寫這些靜態文件……只要記住這樣做的安全性即可。 您實際上是在讓某人對您的服務器執行幾乎任何他想做的事情。

盡管我同意這絕不是解決特定問題的最佳解決方案,但是對於將來可能會發現有用的任何人,我都使用file_get和str_replace來獲得期望的結果。 下面的代碼將使您可以在文件中搜索特定術語,並根據表單輸入將其替換為所需的內容。

<?php
//These are the variables the html file will post to the script.
$filename = $_POST['myFile'];;
$tofind = $_POST['myFind'];;
$toreplace = $_POST['myReplace'];;


$file = file_get_contents($filename);

$end = str_replace($tofind, $toreplace, $file);


 $fp = fopen($filename, "w"); //Open the filename and set the mode to Write
 if(fwrite($fp, $end)) ; //Write the New data to the opened file
 fclose($fp); //Close the File



echo(" File name is $filename ... Finding $tofind .... Replacing with $toreplace .....           Done !");
?> 

盡管這是一個可怕的解決方案,但將其與您的代碼混合即可

$replace = array_key_exists('input',$_REQUEST) ? $_REQUEST['input'] : ''; 
//$replace = sanitize($replace); // there's so much bad with this string
//do the needfull
?>
<form method='GET' action='#'>
   <input type='text' name='input' />
   <input type='submit' />
</form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM