dongruo4601 2014-06-29 11:21
浏览 132
已采纳

如果文件存在,如何删除文件

I am trying to check if the instance of a filename exists (despite it's extension) and then delete it. Here is what I have that is not working...

$username  = $_POST["data"]["username"];

$mask = '../../files/' . $username . '.*';
if (file_exists($mask)) 
{
unlink ($mask);
} 

Can someone please tell me what I'm doing wrong? I know that the first line is correct because it is being used correctly with other commands. Just not sure about the rest. Using PHP 5.2

  • 写回答

1条回答 默认 最新

  • dou4624 2014-06-29 11:24
    关注

    Try:

    $mask = "../../files/".str_replace("/","",$username).".*";
    $glob = glob($mask);
    if( $glob && count($glob) == 1) {
        unlink($glob[0]);
    }
    

    This starts by making your code just a little safer, so a malicious user can't just go around deleting anything they like. It also refuses to delete stuff if there's more than one file matching. Adjust as needed.

    However, a malicious user can still use your code to delete... well, anyone's profile. Might want to guard against that properly ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services