从目录中逐个读取文件

时间:2015-02-08 16:50:37

标签: php

我正在开发一个使用php供个人使用的应用程序。我想要实现的是:

我在目录中有大量图像。我想为每张图片写一些描述。我准备了一个包含3列的数据库表:id,image_name(唯一约束)和描述。 为了使它工作,我开发了一个网页,我将在浏览器中打开每个图像,写一个关于它的描述,保存到数据库,然后单击下一步打开下一个图像,依此类推。

然而,我无法弄清楚如何实现它。如果我这样做:

$dir = "/images/";

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
      echo "filename:" . $file . "<br>";
    }
    closedir($dh);
  }
}

然后,在到达第n张图像之前,我最终会打开n-1张图像。

3 个答案:

答案 0 :(得分:1)

我首先将文件导入数据库。不是实际文件,而只是对文件夹中文件的引用。 (这不是完整的代码,但你会明白这一点)

$files = array_diff( scandir("/path/to/directory"), array(".", "..") ); 
foreach($files as $file) {
    //insert a reference into the database 
    $query = "insert into table_name (image_name) values $file;";
    mysql_query($query);
}

一旦它们到位,您可以通过Id轻松查询它们。

网页看起来像这样:

<?php
$imageId= (int)$_GET['id'];
$row = mysql_fetch_array("select * from table_name where id=$imageId"); 
?>

<html><body>
<a href="?id=<?php echo $imageId + 1; ?>"> Next image </a> 
<img src="<? echo $row['image_name']; ?> ">  
your form here...

并使用例如http://127.0.0.1/images/index.php?id=1

转到您的网页

答案 1 :(得分:0)

使用浏览器你不能这样做,因为在Web请求之间PHP没有保持其状态。

你能做的是:

  1. 将最后一个图像编号保存在一个cookie中 - 在下一个请求中,您将阅读它并跳到所需的编号(您仍然必须跳过)。
  2. 将PHP的整个文件列表发送到您的浏览器,并使用Javascript和AJAX请求在一个页面中浏览它。
  3. 将数据库中的列表和/或当前号码保存在某个临时表中。因此,每次将请求发送到PHP脚本时,它都会首先检查是否存在已保存的数据。

答案 2 :(得分:0)

我要做的是找到一个已经存在于数据库中的图像并请求它的描述,这将使php成为:

if (!empty($_POST['image'])) {
    // Save the image / description in the db
}
$existing = array(); // Fill this array with the image names that exist in the db.
$dir = "/images/";
// Open a directory, and read its contents
$file = null;
if (is_dir($dir)){
    if ($dh = opendir($dir)){
        while (($file = readdir($dh)) !== false){
            if (!in_array($file, $existing)) {
                break;
            }
        }
        closedir($dh);
    }
}
if ($file === null) {
    die('something is wrong, I can not get any files');
}
// set the $file to your view

在html中我会有这样的东西:

<form action="">
    Image: <input name="image" type="text" value="<?php echo $file; ?>"/>
    Description: <input name="description" type="text" value="<?php echo $file; ?>"/>
</form>