取消链接()不起作用

时间:2013-02-22 09:57:33

标签: php file-io unlink

我正在尝试从服务器中删除文件。

我的应用程序的文件位于文件夹名称“/ public_html / app /”;

与应用程序关联的所有图像都位于以下路径中:“/ public_html / app / images / tryimg /”

我正在编写以下代码规范的文件位于“/ public_html / app /".

这是我的代码snipet:

<?php

$m_img = "try.jpg"

$m_img_path = "images/tryimg".$m_img;

if (file_exists($m_img_path))
{
     unlink($m_img_path);
}
// See if it exists again to be sure it was removed
if (file_exists($m_img))
{
          echo "Problem deleting " . $m_img_path;
}
else
{
        echo "Successfully deleted " . $m_img_path;
}
?>

执行上述脚本时,会显示“Successfully deleted try.jpg”消息。

但是当我导航到该文件夹​​时,文件不会被删除。

Apache:2.2.17 PHP版本:5.3.5

我做错了什么?

我是否必须提供图像的相对或绝对路径?

2 个答案:

答案 0 :(得分:1)

您检查错误的路径:

if (file_exists($m_img)) 

当您(尝试)删除(d)$m_img_path时,请用

替换您的支票
if (file_exists($m_img_path))

unlink()返回一个布尔值来指示删除是否成功,因此使用此值更容易/更好:

if (file_exists($m_img_path)) 
{
    if(unlink($m_img_path))
    {
        echo "Successfully deleted " . $m_img_path;
    } 
    else 
    {
        echo "Problem deleting " . $m_img_path;
    }
}

此外,当前目录位于执行脚本的位置,因此在使用相对路径时需要牢记这一点。在大多数情况下,如果可能的话,使用绝对路径可能更好/更容易。

如果您需要服务器上许多文件的路径,您可能希望将绝对路径放在变量中并使用它,因此如果您的服务器配置发生变化,很容易更改绝对位置。

答案 1 :(得分:1)

你错过了一个目录分隔符:

$m_img = "try.jpg"

$m_img_path = "images/tryimg".$m_img;

// You end up with this..
$m_img_path == 'images/tryimgtry.jpg';

您需要添加斜杠:

$m_img_path = "images/tryimg". DIRECTORY_SEPARATOR . $m_img;

您还需要更改第二个file_exists调用,因为您使用的是图片名称,而不是路径:

if (file_exists($m_img_path)) 
相关问题