Hey so I’m trying to clean up my code a bit, and I just need to know: How important is the fopen function in PHP? By this I mean…well I’ve been told that you always need to fclose a file when you’re done with it. This leads me to believe that if a file stays open too long then it gets corrupt in some way?
I don’t know, but the thing is I’ve got an if statement that if the condition is true, it opens the file(s) and writes to it(them). Would it be just as efficient to open all the files for writing/reading at the beginning of the script, and then just include the instruction to actually write to them if the conditional is true??
And while we’re on the topic…if I want to read line by line from a file I’ll simply use the array = file(“filename) shortcut I learned here. Is there a shortcut for writing to a file as well, without having to go through all the fopen stuff? Can I take a file and make it an array, line by line, and by changing that array, change the file? Is there anyway to do that?
Thanks!
I think PHP is smart enough to garbage collect your open files when you are finishing using them. I don’t think the file will be corrupted if you don’t close it unless you write to it unintentionally.
I’m not sure you should worry about efficiency unless you need to. If your code is working and is maintainable, I wouldn’t change where you open files.
You can use
file_put_contents(..)as a shortcut to write to files.