이안의 평일코딩

[PHP] 반복문과 조건문의 활용 (scandir) 본문

Back-end/PHP

[PHP] 반복문과 조건문의 활용 (scandir)

이안92 2021. 4. 2. 11:48
반응형

scandir()

scandir()라는 함수를 통해 데이터 디렉토리 파일 목록을 가져올 수 있다. (배열로 가져옴)

<?php
 $list = scandir('./data');
 var_dump($list);
?>

array(5) { [0]=> string(1) "." [1]=> string(2) ".." [2]=> string(3) "CSS" [3]=> string(4) "HTML" [4]=> string(10) "JavaScript" }

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1><a href="index.php">WEB</a></h1>
    <ol>
        <?php
            $list = scandir('./data');
            $i = 0;
            while($i < count($list)){
                if($list[$i] != '.') {
                    if($list[$i] != '..') {
                        echo "<li><a href=\"index.php?id=$list[$i]\">$list[$i]</a></li>\n";
                    }
                }
                $i = $i + 1;
            }
        ?>
    </ol>
    <h2>
        <?php
            if(isset($_GET['id'])){
                echo $_GET['id'];
            } else {
                echo "Welcome";
            }
        ?>
    </h2>
    <?php
    if(isset($_GET['id'])){
        echo file_get_contents("data/".$_GET['id']);
    } else {
        echo "Hello, PHP!";
    }
    ?>
</body>
</html>

 

반응형
Comments