Cory94bailly Posted February 16, 2009 Share Posted February 16, 2009 Hi, for my log script I am using this: $open = fopen($file, "a") or chmod($file, 0755); //Opening the file. That works great but now I want to put the newest records at the beginning of the file. I tried fopen($file, "w") but it's not exactly what I wanted since it deletes everything else in the file. I also tried fopen($file, "r+") but it seems to do the same exact thing as "w"... Any help? Quote Link to comment https://forums.phpfreaks.com/topic/145395-solved-fopen/ Share on other sites More sharing options...
angelcool Posted February 16, 2009 Share Posted February 16, 2009 I think this is a common logic for any language trying to update a text file, 1.- Read it 2.- Store it in memory 3.- Modify it 4.- Write it If I am right, you are missing to modify it and write it. After fopen() a file you store its value in a variable (in your case: $open), then modify it using a foreach() loop by either adding or appending data to the variable and finally use fwrite() to write. Do not take me too serious on this one though, it is 3 am in L.A. and my eyes are giving up. For example: <?php // Open the file $filename = "/settings.txt"; $fh = fopen($filename, 'r'); //Read the file and store its contents in a variable $contents = fread($fh, filesize($filename)); //close the file fclose($fh); //Read each line of the file and store it in an array (explode returns an array) // If you are on a Windows server, change "\n" to "\r\n" $records = explode("\n", $contents); //Modify the array,either add or append a line foreach ($records as $key=>$recordLine) { //modify array and store new content in an a variable $newContent. } // Open the file (again) $fh = fopen('/settings.txt', 'w'); //write the new content fwrite($fh, $newContent); //close the file fclose($fh); ?> Quote Link to comment https://forums.phpfreaks.com/topic/145395-solved-fopen/#findComment-763298 Share on other sites More sharing options...
PFMaBiSmAd Posted February 16, 2009 Share Posted February 16, 2009 Writing a new line to the start of a file is exceedingly slow because you must read and write the whole existing file every time it is updated and this gets slower as the file size grows. This is why new lines are normally appended to the end of files. If you have some specific need for newer lines to be retrieved first, you should probably be using a database instead of a file. Quote Link to comment https://forums.phpfreaks.com/topic/145395-solved-fopen/#findComment-763300 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.