How can I insert text in a file using PHP?


#1

Hello,

I wanted to create a system which will automatically writes code in javascript based on your actions on front-end,

say for example, on front-end user clicks on button called Create Function, in the back-end my server will automatically creates new file and also creates a function in it, and saves it, now if user clicks on a button called, on call of the function show an alert, now in the bankend how can I insert text (code) inside the function int the file, which user had created dynamically?

Like this I want to give option to my user where they can remove functionality of particular functionality, say like after few hours, user feels, instead of showing an alert, we will add log in console panel of browser, that time, how can I remove particular line from that function and add console functionality in the function?


#3

As far as how you can write files, well… the same way that you wrote the file to begin with. The most simple way will be file_put_contents.

How do you create and manage a coherent file? That’s far more complex, but probably the simplest way will be:
to retrieve the file
slice the file into individual lines
(Insert):
Knowing where the ‘insert point’ is from the top of the file, add lines according to your script’s needs.
(Delete):
Search the array for the starting line of your action, delete X rows from the array starting with that row, where X is the number of rows in that function.
(Both):
Recompile the array into a string and put_contents it again.