dt3999 2010-02-14 10:37
浏览 110
已采纳

用PHP编辑文件

Is there a way to append or remove a line of text from a file using PHP.

I am in the process of writing a hosting control panel for my specific web hosting stack and would like to be able to make changes to the files with minimal requirements to touch the file system, and as such would like not to have to rewrite the whole file to add or remove a configuration option.

  • 写回答

5条回答 默认 最新

  • duankui3838 2010-02-15 00:08
    关注

    Working with files in PHP is full of pitfalls, particularly wrt concurrency and locking. The fact that you are writing config files implies also that you are exposing tasks normally only available to a user with root privileges over the web. You did not mention these things in your post, but your question is trivial in comparison to addressing these issues.

    Regarding your question - although its fairly trivial to implement what you propose (e.g. by exec'ing sed - although you did not did say what OS this is running on) I'd recommend creating a copy of the original file in some other representation - obvious candidates would be a database - where you can apply sequence numbers to the lines and easily create a gap to populate, or a PHP SplDoublyLinkedList stored in the session. Then once the user has effected as many changes as they require, regenerate the file in a single operation from the working representation.

    Note that, ultimately, regardless of how you implement the solution the solution will rewrite the entire file - its just a question of how much of this process is exposed within your code.

    Bear in mind, that what you are doing is just the same as most php web scripts - except while they manipulate and reqrite HTML, you're doing it with a different file type - so you might want to look at how other PHP templating systems are written, and consider whether you can create a template for your config files.

    HTH

    C.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条