【问题标题】:Get File Name With PHP使用 PHP 获取文件名
【发布时间】:2014-09-07 11:08:19
【问题描述】:

我正在使用 php 脚本从文件夹中获取所有图像并对它们进行分页,一切正常,但是我想使用实际的照片名称(文件名)作为 alt 标签,但我发现很难得到这个名字。任何方式都可以使用以下代码完成:

<?php
//The directory to your images folder, with trailing slash
$dir = "cms/gallery/photo/";

//Set the extensions you want to load, seperate by a comma.
$extensions = "jpeg,jpg,gif,png";

//Set the number of images you want to display per page
$imagesPerPage = 3;

//Set the $page variable
if(!isset($_GET['page'])){
    $page = 1;
}else{
    $page = $_GET['page'];
}

//Load all images into an array
$images = glob($dir."*.{".$extensions."}", GLOB_BRACE);

//Count the number of images
$totalImages = count($images);

//Get the total pages
$totalPages = ceil($totalImages / $imagesPerPage);

//Make sure the page you are on is not greater then the total pages available.
if($page > $totalPages){
    //Set the currnet page to the total pages.
    $page = $totalPages;
}

//Now find where to start the loading from
$from = ($page * $imagesPerPage) - $imagesPerPage;

//Now start looping
for($i = $from; $i < ($from + $imagesPerPage); $i++){
    //We need to make sure that its within the range of totalImages.
    if($i < $totalImages){
        //Now we can display the image!
        echo "

            <div class='galleryCellHolder'>
                <div class='galleryCell'>
                    <a class='fancybox' rel='group' href='{$images[$i]}'><img class='galleryPhoto' src='{$images[$i]}' alt='I NEED THIS TO BE THE FILE NAME'></a>
                </div>
            </div>

        ";
    }
}

//Now to display the page numbers!
for($p = 1; $p <= $totalPages; $p++){
    if($p == $page){
        $tmp_pages[] = "<strong class='pagination'>{$p}</strong>";
    }else{
        $tmp_pages[] = "<a class='pagination' href='?page={$p}'>{$p}</a>";
    }
}
?>

【问题讨论】:

  • 我的回答符合你的要求吗?

标签: php file directory


【解决方案1】:

使用basename()

$filename = explode('.', basename($images[$i]));
echo "
    <div class='galleryCellHolder'>
        <div class='galleryCell'>
            <a class='fancybox' rel='group' href='{$images[$i]}'><img class='galleryPhoto' src='{$images[$i]}' alt='" . $filename[0] . "'></a>
        </div>
    </div>    
";

【讨论】:

  • 可以,但我希望只显示没有文件夹路径和扩展名的标题
  • 现在给我:Parse error: syntax error, unexpected '[', expecting ',' or ';' in C:\AppServ\www\---.com\photo-gallery.php on line 95
  • 好吧,这消除了错误,但 alt 标记中没有显示任何内容
  • @user3177012 如果您使用的 PHP 版本低于 5.2$pathinfo["filename"] 将无法工作。取而代之的是,使用我的答案的编辑版本(我现在将对其进行编辑)
  • 谢谢,现在可以了!它仍然显示 .jpg 扩展名,但我想我可以忍受 - 我正在使用 PHP 版本 5.2.6
【解决方案2】:

在你的循环中做:

var_dump(basename($totalImages[$i]));

或者您也可以检查:

var_dump(pathinfo($totalImages[$i]));

还有basename,带有目录名,扩展名等。

【讨论】:

  • 谢谢,但我仍然不确定将它放在我的脚本中的确切位置!
  • $totalImagesint 类型,而不是 array。包含图像的数组是$images
猜你喜欢
  • 2010-12-17
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
相关资源
最近更新 更多