【问题标题】:Perform Delete, Edit and search operation on a file using php使用 php 对文件执行删除、编辑和搜索操作
【发布时间】:2019-09-20 04:21:23
【问题描述】:

我有一项任务要做,我必须列出目录及其文件,但我不明白如何删除文件或编辑目录中的特定文件,任何帮助将不胜感激谢谢。

<?php
  error_reporting(0);

 if(isset($_GET['dir']))
{
 // /$path = 'E:\xampp\\'.$_GET['dir'];
 $path = $_GET['dir'];
}
 else
{
    $path = 'E:\xampp\\';
}

 if(is_dir($path))
 {
    $arrDir = scandir($path);
    echo "<ul>";

 foreach ($arrDir as $key => $value) 
 {

    echo "<a href='http://localhost/vishrut/FileUpload/filelist.php? 
    dir=".$path.'/'.$value."'>".$value.'</a><br>';   
 }

 echo "</ul>";

}
 else
{    
    echo "<textarea>";
    echo file_get_contents($path);
    echo "</textarea>"."<br>";     
}   

?> 

【问题讨论】:

  • 你看到我的回答了吗?

标签: php file file-handling


【解决方案1】:

有很多PHP的函数来处理文件:https://www.php.net/manual/en/ref.filesystem.php

根据您的需要,请参阅以下内容:

所以,修改文件的步骤可能是:

  1. 通过file_get_contents获取完整内容:

    $contents = file_get_contents($filePath);
    
  2. 将您的编辑应用到$contents 内容:

    $newContents = ...
    
  3. 覆盖文件内容:

    file_put_contents($filePath, $newContents);
    

删除文件很简单:

unlink($filePath);

请务必注意,您的代码会受到注入,因为您不检查使用 $_GET 传递的用户数据。

如果您的脚本将仅由您使用没关系,您必须检查所有用户输入:Web 编程的第一条规则是永远不要相信您的用户!此外,受信任的用户可能会在 url 中写入错误的字符,这可能会产生意想不到的结果(例如删除错误的文件!)

阅读https://www.php.net/manual/en/mongodb.security.script_injection.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多