2018년 5월 21일 월요일

[PHP예제] 128 디렉터리 안의 이미지를 목록으로 표시


128.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>디렉터리 안의 이미지를 목록으로 표시</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>
<div>
<?php
// h() 함수
require_once 'h.php';

// 이미지를 목록으로 표시할 디렉터리를 설정
$dirName = __DIR__;
if( !is_dir($dirName) )
{
  die('디렉터리가 존재하지 않음');
}

echo "<p>디렉터리명(상대 경로) : $dirName <br>";
echo "절대 경로: " . realpath($dirName) . "</p>";
echo "<p>디렉터리 안의 이미지 목록</p>";

// 디렉터리를 확인
$dir = scandir($dirName);

// 디렉터리 안의 이미지를 목록으로 표시
foreach( $dir as $d )
{
  $path = $dirName . '/' . $d;

  // '.'에서 시작하는 항목과 디렉터리를 제외함.
  if( strpos($d, '.') === 0 || is_dir($path) )
  {
    continue;
  }

  // getimagesize() 함수에서 이미지 파일인지 확인
  if( @getimagesize($path) !== false )
  {
    // 확장자가 GIF, PNG, JPG의 이미지를 표시함
    $extension = pathinfo($path, PATHINFO_EXTENSION);

    if( !in_array($extension, array('gif', 'png', 'jpg', 'jpeg')))
    {
      continue;
    }

    $imageFile = '128_display.php?file=' . rawurlencode($d);

    echo '<a href="' . h($imageFile) . '" target="_blank">';
    echo '<img src="' . h($imageFile) . '" width="100" alt="사진">';
    echo "</a>&nbsp;";
  }
}
?>
</div>
</body>
</html>

128_display.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
// GET 쿼리를 통해 이미지 파일명을 받음
if( !isset($_GET['file']) )
{
  die('표시할 파일이 지정되어 있지 않음');
}
$fileName = basename($_GET['file']);

$dirName = __DIR__;
$subDirList = array('output' => 1); // 표시 가능한 디렉터리명 목록

// GET 쿼리에 디렉터리명이 지정되어 있으면 확인하여 추가함
if( isset($_GET['dir']) )
{
  if( !isset($subDirList[$_GET['dir']]) )
  {
    dir('잘못된 지정임');
  }

  $path = $dirName . '/' . $_GET['dir'] . '/' . $fileName;
}
else
{
  $path = $dirName . '/' . $fileName;
}

// 이미지를 출력함
if( file_exists($path) && ($imageSize = getimagesize($path)) !== false )
{
  // HTTP 헤더가 전송되지 않으면
  // 이미지를 단독 표시로 처리해 HTTP 헤더를 전송함
  if( !headers_sent() )
  {
    header('Content-Type: ' . $imageSize['mime']);

    // 인터넷 익스플로러가 Content-Type 헤더를 무시하지 않게 함
    header('X-Content-Type-Options: nosniff');
  }
  readfile($path);
}
else
{
  echo "이미지를 출력할 수 없음";
}


댓글 없음:

댓글 쓰기