append to a php file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tarja311
Forum Commoner
Posts: 73
Joined: Fri Oct 20, 2006 10:57 pm

append to a php file

Post by tarja311 »

Hey guys. I am having trouble "replacing" a string in a php/text file. I've created an Update script that is supposed to update a previous php configuration script with my new one. The problem i am having is i cannot replace the ?> with a "" so i can append to the file, then later closing it with the ?> tag.

I know it's probably really easy to do, i just can't get my head over it.

Code: Select all

// info that is to be added.
$updatedinfo = '

$text 	= "some config info";
...

?>';


// check if script exists.
$exist = fopen("configfile.php", "r");
		
if($exist)
{
 	
	$fp = fopen("configfile.php", "a");
 	$cfile = file("configfile.php");

	foreach ($cfile as $line_num => $cfile) 
	{
	 	ereg_replace("?>","",$cfile);
 		htmlspecialchars($cfile);   		
   		echo "<br />"; 		
	}

	fwrite($fp, $cfile);
	fclose();

} // end if.
User avatar
tecktalkcm0391
DevNet Resident
Posts: 1030
Joined: Fri May 26, 2006 9:25 am
Location: Florida

Re: append to a php file

Post by tecktalkcm0391 »

Try this:

Code: Select all

// info that is to be added.
$updatedinfo = '

$text 	= "some config info";
...

?>';


// check if script exists.
$exist = fopen("configfile.php", "r");
		
if($exist)
{
 	
	$fp = fopen("configfile.php", "a");
 	$cfile = file("configfile.php");

	foreach ($cfile as $line_num => $cfile) 
	{
	 	$cfile.= str_replace("?>","",$cfile);
 		$cfile.= htmlspecialchars($cfile);   		
   		$cfile.= "<br />"; 	
	}

	fwrite($fp, $cfile);
	fclose();

} // end if.
Don't know if it'll work, but you can try.
Last edited by tecktalkcm0391 on Wed Feb 21, 2007 4:16 pm, edited 2 times in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

You don't have to remove the trailing ?>. As long as there isn't text (a single carriage return is fine) between the close and open tags, PHP won't really skip a beat.

file_exists(), is_file(), is_readable() and is_writable() may be of interest though.
tarja311
Forum Commoner
Posts: 73
Joined: Fri Oct 20, 2006 10:57 pm

Post by tarja311 »

ok, thank you. :)
You don't have to remove the trailing ?>. As long as there isn't text (a single carriage return is fine) between the close and open tags, PHP won't really skip a beat.
I totally forgot about that. Thanks.
Post Reply