我正在尝试从服务器中删除文件。
我的应用程序的文件位于名为“/public_html/app/”的文件夹中;
与应用程序关联的所有图像都位于以下路径:"/public_html/app/ images /tryimg/“
我在其中编写以下代码规范的文件位于"/public_html/app/“。
下面是我的代码片段:
<?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 try.jpg“。
但当我导航到该文件夹时,该文件并未被删除。
Apache: 2.2.17 PHP版本: 5.3.5
我做错了什么?
我必须给出图像的相对路径还是绝对路径?
发布于 2013-02-22 18:13:34
您缺少目录分隔符:
$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)) 发布于 2013-02-22 18:05:19
您检查了错误的路径:
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;
}
}此外,当前目录位于执行脚本的位置,因此在使用相对路径时需要记住这一点。在大多数情况下,如果可能的话,使用绝对路径可能更好/更容易。
如果您需要服务器上许多文件的路径,您可能希望将绝对路径放在一个变量中并使用它,这样,如果您的服务器配置发生变化,则很容易更改绝对位置。
https://stackoverflow.com/questions/15021390
复制相似问题