如何从PHP目录中选择一个图像?

时间:2015-03-15 16:59:18

标签: php

我知道图片名称我不知道图片扩展名(jpg,gif等)(代码自动选择)。目录名称“上传”

我在上传文件夹中有很多图像,如(Image1,Image2,Image3),但我只想选择一个图像(image1 . (jpg)(gif)(png))。请给我一些PHP代码,用于从任何扩展名的目录中选择图像。

    $img_detail = '11_detail'; // i wanna select this image
    $dir    = 'upload/advertisement/';
            $files = scandir($dir);
            foreach($files as $file){

            echo $file.'<br>';

            }
        // Code showing result like thi
//         11.swf
//         13.gif
//         14.gif
//         15.gif
//         16.jpg
//         16_detail.gif // i wanna select this image
//         index.php

所有图片扩展程序不相同

1 个答案:

答案 0 :(得分:0)

享受!

        $ad_id = '11';
        $addata = ad_data($conn, $ad_id, 'ad_img'); // Function

        $addetail = $ad_id.'_detail'; // this is my file name

        $dir    = 'upload/advertisement/';
        $files = scandir($dir);
        foreach($files as $file){

        $file = explode('.', $file);
        $currentname = current($file); // i have select current name
        $ext = end($file); // for final result 
    //  echo $firstname. '-'.$ext.'<br>'; // test
            if($currentname == $addetail){ // matching image name with required name
            $real_file = $currentname.'.'.$ext; // after matching use real extension 
            }
        }

        if(empty($real_file)){ // if file not found 
            echo $ad_id.'.'.$addata['ad_img'];
        }else{ // enjoy 
            echo $real_file;
        }