如何在 php 中取消文件安全链接


How to unlink file securly in php?

我需要在 php 中使用unlink()函数删除/var/www/mysite/postImage文件夹中的图像文件。但我绝对担心是否有人入侵了我的网站并正在使用它..或。并尝试删除上层文件夹中的某些内容。我正在使用JQuery发送路径,因为它是客户端编程,所以很危险。我知道,我可以在上传文件时绕过点,但是如果有人通过添加点来更改客户端的路径怎么办?我的问题是如何防止某人这样做?

  1. 确保 apache 用户具有适当的权限(仅在网站目录中写入)
  2. 从路径中切..,清理并验证路径是否正确。
  3. 你也可以使用 realpath() 函数。

经验法则应该是,您应该最不依赖来自客户端的数据。

现在根据您的问题,您似乎正在发送要删除的完整文件路径。

所以恕我直言,你应该只发送文件名,让服务器端php决定(附加)要删除文件的目录。

// example
$filename = $_POST['fname']; // something like xyz.png
$filename = str_replace('/','',$filename); // strip any forward slash.
if(empty($filename)){
die('File Name Invalid'); // seems like all the characters in file name were slashes.
}
$directory = 'some/folder/that/contain/images/postImage/';
$filepath = $directory . $filename;
unlink($filepath);

现在关于其他人使用此功能,只需保留登录系统,并检查用户是否已登录。