繁体   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