9

我想从 PHP 中的文件夹中删除一个文件,但我只有该文件的路径,是否可以提供取消链接的路径?例如

unlink('path/to/file.txt');

如果这不起作用,那么摆脱这些文件的唯一方法是在 path/to/ 目录中创建一个 .php 文件,并以某种方式将其包含在我的文件中,然后调用那里的方法来删除文件,对吗?

4

9 回答 9

19

有一个简单的方法来解决您的问题

使用此代码从文件夹中删除文件

$_SERVER['DOCUMENT_ROOT']

这可以在 unlink 函数中使用

工作代码

     unlink($_SERVER['DOCUMENT_ROOT'] . "/path/to/file.txt");
于 2013-07-13T06:05:45.493 回答
5

看看unlink文档:

bool unlink ( string $filename [, resource $context ] )

文件名 文件
的路径。

所以它只需要一个字符串作为文件名。

确保从执行脚本的位置可以访问该文件。这不是绝对路径的问题,但您可能会遇到相对路径的问题。

于 2011-02-15T16:46:19.030 回答
5

unlink 适用于路径。

说明 bool unlink ( string $filename [, resource $context ] )

删除文件名。类似于 Unix C unlink() 函数。失败时将生成 E_WARNING 级别错误。

文件名

Path to the file.

如果权限被拒绝错误出现问题,有时是由于您尝试将层次结构中较高文件夹中的文件删除到您的工作目录(即尝试删除以“../”开头的路径时) .

所以要解决这个问题,您可以使用 chdir() 将工作目录更改为要取消链接的文件所在的文件夹。

<?php
    $old = getcwd(); // Save the current directory
    chdir($path_to_file);
    unlink($filename);
    chdir($old); // Restore the old working directory   
?>
于 2011-02-15T16:49:35.077 回答
2

不要忘记检查文件是否存在,否则会报错:

$file_with_path = $_SERVER['DOCUMENT_ROOT'] . "/path/to/file.txt";
if (file_exists($file_with_path)) {
  unlink($file_with_path);
}
于 2013-08-18T11:18:22.233 回答
1

您可以将 unlink 与路径一起使用。

您也可以对目录执行取消链接,只要您先将其清空即可。

这是手册: http: //php.net/manual/en/function.unlink.php

于 2011-02-15T16:45:32.747 回答
0

根据文档,unlink接受路径的字符串参数。

http://php.net/manual/en/function.unlink.php

换句话说......你有你需要删除文件。

于 2011-02-15T16:46:39.037 回答
0

不仅没问题,它还是在 PHP 中删除文件的唯一方法(除了系统调用)。

于 2011-02-15T16:46:56.537 回答
0

我们可以使用这段代码

$path="images/all11.css";

if(unlink($path)) echo "Deleted file ";
于 2016-10-12T06:22:33.473 回答
-4
if (isset($_POST['remove_file'])) {
           $file_path=$_POST['fileremove'];
     // chown($file_path, 'asif');
     // echo $file_path;
    if (file_exists($file_path)) {
          unlink($file_path);
        echo "file deleted<br> the name of file is".$file_path."";

        # code...
    }
    else
        echo "file is not deleted ".$file_path."";
    # code...
}
于 2017-02-02T10:39:44.517 回答