简体   繁体   中英

Updating HTML files using PHP from form input

Basically, I want to update static HTML files with code snippets input by users from a standard form. I understand how updating the files work, I'm just unsure as to how I go about including the code input from the form to my php file, which is shown below.

<?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';

?>

Any help greatly appreciated.

I would approach this a bit differently. I suggest having a template file aside from the one being modified. That way, you are always modifying a fresh copy instead of having to worry about what changed in the new version.

If your needs become more advanced beyond simply dropping in some markup, I might suggest using a DOM parser.

Finally, I'm sure you have a good reason for writing these static files... just remember the security implications of doing so. You're effectively letting someone do almost anything they want to your server.

Although I agreed it was in no way the best solution to the specific problem, for anyone that may find this useful in the future I used file_get and str_replace to achieve desired results. The code below will allow you to search a file for a specific term and replace with whatever you want based on form input.

<?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 !");
?> 

Though it's a horrible solution, mixed with your code this will do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM