Edit a file with a form

driveflexfuel

New Member
Messages
159
Reaction score
0
Points
0
I have a file that i wish to edit using a form. I only want to load and edit a specific portion of the page. If anyone can help with this I thank you ahead of time.

This is what the code looks like
Code:
coding here

<!--Load from here-->
This is the editable portion of the page i wish to load into the form
<!--Load to here-->

more coding here
 

VPmase

New Member
Messages
914
Reaction score
1
Points
0
One way you can do it is by using multiple files and only loading the editable file. That would probably be the easiest and fastest way.
 

garrettroyce

Community Support
Community Support
Messages
5,609
Reaction score
250
Points
63
One way you can do it is by using multiple files and only loading the editable file. That would probably be the easiest and fastest way.

This is a good way to do it. Also, when you edit a file, depending on how you open the file, it may only be accessible to one person at a time. So, if you plan on making a file editable by more than one user at once, the users may get an error if someone is already editing it. This also includes you, if you are trying to edit a file using the same file, as VPmase mentioned :p

I usually save all writing until the very last possible moment to minimize the file locking problems. Also, using fclose() when you don't need a file handle and closing any open resources can help minimize this problem as well.
 

gomarc

Member
Messages
516
Reaction score
18
Points
18
PHP:
<?php
 
//Variables to edit
$filename = "file2edit.txt"; //File to edit
$startmark= "<!--Load from here-->";
$endmark  = "<!--Load to here-->";
 

$source = file_get_contents($filename)
  or exit("</br>Problem reading <b>'".$filename."'</b> (check file name)");
  
$fstart = strpos($source, $startmark) 
  or exit("</br>Error: Start mark on file not found");
$fstart = $fstart + strlen($startmark);  

$fend = strpos($source, $endmark) 
  or exit("</br>Error: End mark on file not found");  

//Split the file
$part1 = substr($source, 0, $fstart);
$part2 = substr($source, $fstart , ($fend-$fstart));
$part3 = substr($source, $fend , (strlen($source)-$fend));

?>

<FORM METHOD="POST" ACTION="save_changes.php">

<P>Edit your file <?=$filename?>:<br>

<TEXTAREA NAME="part2" COLS=80 ROWS=15 WRAP=virtual>
<?=$part2?>
</TEXTAREA></P>
<input type="hidden" name="fname" value="<?=$filename?>">
<input type="hidden" name="part1" value="<?=$part1?>">
<input type="hidden" name="part3" value="<?=$part3?>">

<P><INPUT TYPE="submit" NAME="submit" VALUE="Save Changes"></P>

</FORM>
And the file save_changes.php is
PHP:
<?php

IF (ISSET($_POST['fname']))
{

  $Newfile = $_POST['part1'] . $_POST['part2'] . $_POST['part3'];

  $file = fopen($_POST['fname'],"w");
  fwrite($file,$Newfile);
  fclose($file);

  echo "<br>Changes to file <b>".$_POST['fname']."</b> have been saved";

}
else
{
  echo "<br>Nothing done";
}

?>
 
Top