【问题标题】:PHP opendir() not opening a subdirectoryPHP opendir() 没有打开子目录
【发布时间】:2010-12-10 04:24:39
【问题描述】:

我制作了一个 php 图片库,它应该列出“pics”文件夹的所有子目录,点击后,会显示文件夹中的第一张图片,并带有指向上一张和下一张照片的链接。当它在第 20 行列出“pics”文件夹的子目录时,没有返回任何内容。此外,下一个和上一个链接始终显示指向“专辑”页面的链接,而不是下一个图像。

我做错了什么?对我的代码的任何批评也将不胜感激。

<?
//Return the contents of a folder which are images as an array
function dirContents($folder){
if ($handle = opendir($folder)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != ".." && !is_dir($file) && (pathinfo($file,PATHINFO_EXTENSION) == 'jpg')) {
            $contents[] = $file;
            echo "$file</br>";
        }
    }
    closedir($handle);
}   
    return $contents;
}

if (!isset($_GET['album'])){
    //List all the albums from the pics folder
    echo '<div class="subhead">Albums</div>';
    echo '<ul>';
    if ($handle = opendir("./pics")) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != ".." && is_dir($file)) {
                echo '<li><a href="?page=gallery&album='.$file.'&i=0">'. $file. '</a></li>';
            }
        }
        echo '</ul>';
        closedir($handle);
        }   
}
else{
// Include some input validation here to see if $album is actually a subfolder of pics
    $album = $_GET['album'];
        if (!isset($_GET['i']))
            $i = 0;
        else
            $i = $_GET['i'];
    $ip = $i-1;
    $in = $i+1;
    $images = dirContents($album);
    $len = count($images);
    echo "<div class=\"subhead\">$album, Num photos = $len</div>";
    echo '<div class="viewer">';
        if ($ip < 0)
            echo '<a href="?page=gallery">Albums</a>';
        else
            echo "<a href=\"?page=gallery&album=$album&$ip\">Albums</a>";
    echo "<img src=\"$album\\$images[$i]\" />";
        if ($in >= count($album))
            echo '<a href="?page=gallery">Albums</a>';
        else
            echo "<a href=\"?page=gallery&album=$album&$in\">Next</a>";
    echo '</div>';
}

echo 'All images appear here with the given consent of those persons that appear within them';
?>

【问题讨论】:

    标签: php opendir


    【解决方案1】:

    ./pics 是一个目录名称​​相对于当前工作目录 (./),除非您事先明确使用 chdir 导航到该目录,否则您不能使用它,您必须提供opendir 的绝对目录路径。

    opendir(dirname(__FILE__) . '/pics');
    

    【讨论】:

    • 你可以通过dirname(__FILE__)获取当前文件的目录(5.3以上版本为__DIR__
    • 当我使用 PATH_SEPARATOR 时,它返回一个分号 ';'。所以我收到警告:Warning: opendir(C:\php;pics,C:\php;pics): The system cannot find the file specified. (code: 2) in C:\php\gallery.php on line 21
    猜你喜欢
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2016-08-03
    相关资源
    最近更新 更多