[PHP] Keep writing to text file

I can write to a textfile, but each time I write to it the old data get’s replaced with the new data.

I need the file to keep all the records, not just the current.


<?php

// request varibales from flash form
$strCombo = $_POST['Combo'];
$strTown = $_POST['Town'];
$strEmail = $_POST['Email'];
$strName = $_POST['Name'];
$strCounty = $_POST['County'];
$strWebsite = $_POST['Website'];
$strCompany = $_POST['Company'];
$strPostcode = $_POST['Postcode'];
$strEnquiry = $_POST['Enquiry'];
$strAddress = $_POST['Address'];
$strTel = $_POST['Tel'];
$strFax = $_POST['Fax'];

// open text file
$fp = fopen("contacts.txt", "w");
if(!$fp){
	echo "Could not open the file.  Please try again later. ";
	exit;
}
$inputString = "Name: " . $strName . "
 Email: " . $strEmail;
fwrite( $fp, $inputString );
fclose( $fp );

?>

Thanks!!

you could do this:


   <?php 
  
 // request varibales from flash form 
 $strCombo = $_POST['Combo']; 
 $strTown = $_POST['Town']; 
 $strEmail = $_POST['Email']; 
 $strName = $_POST['Name']; 
 $strCounty = $_POST['County']; 
 $strWebsite = $_POST['Website']; 
 $strCompany = $_POST['Company']; 
 $strPostcode = $_POST['Postcode']; 
 $strEnquiry = $_POST['Enquiry']; 
 $strAddress = $_POST['Address']; 
 $strTel = $_POST['Tel']; 
 $strFax = $_POST['Fax']; 
  
  $data = file_get_contents("contacts.txt");
 // open text file 
 $fp = fopen("contacts.txt", "w"); 
 if(!$fp){ 
 	echo "Could not open the file.  Please try again later. "; 
 	exit; 
 } 
 $inputString = "Name: " . $strName . "
 Email: " . $strEmail; 
  $newData = $data."
".$inputString;
 fwrite( $fp, $newData ); 
 fclose( $fp ); 
 ?>  
  

edit: or use “a+” mode for opening the file but I’m not sure abotu that

:thumb:

I just did a quick test with a+ and it worked… :slight_smile:


<?php

	// request varibales from flash form
	$strCombo = $_POST['Combo'];
	$strTown = $_POST['Town'];
	$strEmail = $_POST['Email'];
	$strName = $_POST['Name'];
	$strCounty = $_POST['County'];
	$strWebsite = $_POST['Website'];
	$strCompany = $_POST['Company'];
	$strPostcode = $_POST['Postcode'];
	$strEnquiry = $_POST['Enquiry'];
	$strAddress = $_POST['Address'];
	$strTel = $_POST['Tel'];
	$strFax = $_POST['Fax'];

	// open text file
	$fp = fopen("contacts.txt", "a+");
	if (!$fp)
	{
		echo "Could not open the file.  Please try again later. ";
		exit;
	}
	$inputString = "Name: " . $strName . "
 Email: " . $strEmail;
	fwrite( $fp, $inputString );
	fclose( $fp );

?>

Thanks :slight_smile:

yea, you should use a+… only, it writes the data onto the back of the file…

:p: