如何在php中读取目录中的文件

时间:2014-03-15 06:38:26

标签: php

我想使用php读取目录中的文件.. 详细地: 我在php中创建了一个多文件上传器,这是我的代码

顶部:

<?php
  session_start();
  $name=$_SESSION['albumname'];
  echo '<h3 align="center">You are upload image in album '.$name.' </h3>';
  $mk=@mkdir("../galleryimg/$name", 0755);

?>


形式

<form enctype="multipart/form-data" action="" method="post">
  <br>
  <p class="button-height">
    <span class="input file"><span class="file-text"></span><span class="button compact">Select files</span><input type="file" multiple="" class="file withClearFunctions" value="" id="special-input-1" name="file[]" style="height:30px;"></span>
  </p>
  <a class="button icon-new-tab add_more" href="javascript:void(0)">Add nore files</a>
  <button class="button green-active" name="button">Upload</button>
</form>


用于添加多个文件项的脚本

<script type="text/javascript">
$(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<p class='button-height'><span class='input file'><span class='file-text'></span><span class='button compact'>Select files</span><input type='file' multiple='' class='file withClearFunctions' value='' id='special-input-1' name='file[]' style='height:30px;'></span></p>");
    });
});
</script>


php for upload

<?php
if(isset($_POST['button'])) {
  $target_path = "../galleryimg/".$name."/";

  for($i=0; $i<count($_FILES['file']['name']); $i++){
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
      echo "The file has been uploaded successfully <br />";
    } 
    else{
      echo "There was an error uploading the file, please try again! <br />";
    }
  }
}
?>


此阅读目录

<?php
if ($handle = opendir('../galleryimg/'.$name)) {
  /* This is the correct way to loop over the directory. */
  while (false !== ($entry = readdir($handle))) {
    echo "$entry"."<br>";
  }

  closedir($handle);
}
?>


现在我想得到dir =&#39; ../ galleryimg /&#39;。$ name的文件名,用于输入数据库,其输出为
输出

..
108e196207d5b79aabd4ff1aece93ed61.png


我的问题 我想减去第一行怎么做(..)。

2 个答案:

答案 0 :(得分:1)

使用GLOB代替

$files = glob('../galleryimg/'.$name.'/*');
var_dump($files);

应该为您提供文件夹中的文件数组。

将您的阅读目录代码更改为:

<?php

$files = glob('../galleryimg/'.$name.'/*');

foreach($files as $file) {
  echo basename($file);
}

?>
如果你只想匹配png扩展名的文件,请执行以下操作。

$files = glob('../galleryimg/'.$name.'/*.png');

答案 1 :(得分:0)

..代表父文件夹。只需在循环中添加一个if语句即可消除它。