Page 1 of 1

append to a php file

Posted: Wed Feb 21, 2007 4:09 pm
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.

Re: append to a php file

Posted: Wed Feb 21, 2007 4:15 pm
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.

Posted: Wed Feb 21, 2007 4:15 pm
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.

Posted: Wed Feb 21, 2007 4:35 pm
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.