I have seen something similar in another thread. You might find some parts of that post useful, not everything of course, but I think it is worth checking out. 
http://stevenrgerst.com/t16-xi/02/articles-nydpoEP-765/function.file-put-contents/page/10/