正在尝试用PHP和XPath删除目录中ID匹配的文件


Trying to delete ID matched file in directory with PHP and XPath

我使用unlink()方法删除文件,但我认为从XML文件中获取字符串的语法应用了错误的值。文件仍然未删除,但好消息是脚本返回true,并且仍然从XML中删除帖子。

我的HTML表单blog.php发送$_POST["CHECK"]值:

<html>
<body>
<form method="post" action="remove_post.php">
   <input type="hidden" name="CHECK" value="pst_02-02-2014_02:00:00pm"  />
   <input type="submit" name="CLOSE" value="Delete Post"  />
</form>
</body>
</html>

我的XML文件:data.xml

<?xml version="1.0" encoding="UTF-8"?>
<blog>
    <posting id="pst_01-01-2014_01:00:00pm">
        <date>01-01-2014</date>
        <time>01:00:00pm</time>
        <title>Coming!</title>
        <content>Blog Posts soon!</content>
    </posting>
    <posting id="pst_02-02-2014_02:00:00pm">
        <date>02-02-2014</date>
        <time>02:00:00pm</time>
        <title>A Blog!</title>
        <content>Blog Posts coming soon!</content>
        <image>thumb.jpg</image>
    </posting>
</blog>

我的PHP文件:remove_post.php

<?php
if ( isset( $_POST["CLOSE"] ) )
   {
   $check = $_POST["CHECK"] ;
   $doc = new DOMDocument() ;
   $doc -> load( "data.xml" ) ;
   $xpath = new DOMXPath( $doc ) ;
   $post_element = $xpath -> query( "/blog/posting[@id='$check']" ) ;
   $image_element = $xpath -> query( "/blog/posting[@id='$check']/image" ) ; // Suspected problem
   $image = "blog_images/" . $image_element -> firstChild ; // Suspected problem
   foreach ( $post_element as $post )
      {
      unlink( $image ) ;
      $post -> parentNode -> removeChild( $post ) ;
      }
   $doc -> save( "data.xml" ) ;
   header( "Location: blog.php" ) ;
   }
?>

并且我已经检查了我的文件权限:

文件夹(所有者)权限:/blog_images/

  • 读取
  • 写入
  • 执行

文件夹(公共)权限:

  • 读取
  • 执行

文件(所有者)权限:thumb.jpg

  • 读取
  • 写入

文件(公共)权限:

  • 读取

如果元素存在,在获得xpath值后,它将返回一个DOMNodeList,这意味着您必须首先访问它:

if($image_element->length > 0) { // if it exists
    $image_name = $image_element->item(0)->nodeValue;
                                  // ^ directly access it if you're expecting one value
    // thumbs.jpg
}

或者你也可以循环它:

foreach($image_element as $e) {
    echo $e->nodeValue . '<br/>';
}

现在取消链接:

unlink('blog_images/' . $image_name); // or you can add a file_exists() there just to be sure