Spent most of the week doing plugin development, and you wouldn’t believe the issues I was having with writing PHP code that enables to read/write/open/close files onto the server. There is plenty of information about the functions and how to implement them, not so much information on tips and tricks on real world implementations. Below I will highlight a few points I learnt along the way.
-
Make sure what you write to the file is encoded correctly: When you write a string to a text file or so forth, you cannot just write it without properly encoding the data. Especially if you plan on running the data through Excel or some other program for further indepth analysis.
In PHP, and for most standard types of processing, utf8_encode(string) is the best and easiest way to properly encode your data. By running your string through this function before anything else is done, such as writing to the file, is your first step toward having it easy to read and extract data from later on.
-
Make sure you use correct end of line characters: In PHP, for a particular string that you are compiling, it is best to use double quotes “” rather than singles ‘ ‘ because this enables you to correctly end the line and start a new one in both Windows and Mac environments. I took this lesson from university as well, when I was working with a sample text file that used \n and was constantly erroring because it wasn’t encoded properly to be read on linux and OS X. The solution, at the end of your string, append \r\n to cover both your bases and you will not have to worry about these little issues further down the track.
-
Write to the absolute path, not the URL: This is probably the most important one of all the points I took away from this project. I had to write a file to a particular sub-directory with the url: http://www.example.com/dev/logs. Now I built the URL with a function, I had created the directory on the server and set up the permissions, but it failed to write and spat out error after error.
After a few Google searches here and there, it turns out the secret is that you do not write to the URL but to the path of the sub-directory on the server. In this case being root-path/~test/public_html/dev/logs. Once that was setup up, and making sure the path was complete, everything worked like a dream. To make it easy for myself, I used $_SERVER["DOCUMENT_ROOT"]; to grab the path to the root, and modded my URL builder function to take care of the rest.
Now I know most of the information presented here is at a fairly basic level, but as someone that has not done much file handling with PHP or many other web languages (I’m too used to just dumping everything in a database) it was a nice little learning curve to brush up on my skills. Now I know some of this isn’t that secure, so if anyone has some security recommendations about how to protect yourself correctly when writing to the server, leave a note in the comments and I will adjust the post.