728x90

홈페이지에 접속시 index.php 처리 흐름도는 다음 그림과 같다.


프로그램에서 중요한 것은 어떤 로직으로 그릴것인가 하는 점이다.

사용하는 언어에 따른 문법, 사용법은 당연히 익혀야 한다.


1. index.php 파일에는 순수한 PHP 코드만으로 session 이 있으면 바로 메인페이지로 접속하도록 처리한다.

    session 정보가 없으면 로그인 화면을 띄우도록 한다.

    <?php
    if(!isset($_SESSION)) {
        session_start();
    }
    if(isset($_SESSION['userID']) && !empty($_SESSION['userID'])){
        // 세션 정보가 있으면
        include "main.php";       
    } else {
        // 세션 정보가 없으면
        include "loginForm.php";
    }
    ?>


    이 골격 기반위에 mobile 접속체크 기능을 추가할 수도 있다.

    추가한다면 loginClass.php 파일안에 mobile 체크 함수를 추가할 수 있다.


2. loginForm.php 파일에는 HTML header, body 정보가 들어가 있다.

    - 로그인 정보는 ID, PW 정보이므로 암호화하여 전송하는 것이 안전하다.

    - POST 전송방식으로 전송하여 ID,PW 정보 내용이 보이지 않도록 한다.

    - POST 전송방식 loginForm.php 파일

    <!DOCTYPE html>
    <html>
    <head>
        <title>로그인</title>
        <meta charset="utf-8" />    
        <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0,user-scalable=no"/>
        <meta http-equiv="cache-control" content="no-cache" />
        <meta http-equiv="expires" content="0" />
        <meta http-equiv="pragma" content="no-cache" />

        <!-- Include jQuery Mobile stylesheets -->

        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.css">

        <!-- Include the jQuery library -->

        <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>

        <!-- Include the jQuery Mobile library -->

        <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>

        <!-- 개발자 본인이 만든 jQuery -->

        <script src="js/loginScript.js"></script>
    </head>
    <body>
    <div id="content" data-role="content" style="margin-top:5%;">
        <center>
        <form id="loginForm" method="post" action="#" >
            <input type="text" name="userID" id="userID" value="" placeholder="아이디" style="width:50%" />
            <input type="password" name="password" id="password" value="" placeholder="패스워드" style="width:50%"/>
            <button type="submit" data-inline="true">로그인</button>
            <button type="reset" data-inline="true">다시작성</button>
        </form>
        </center>
    </div>
    </body>
    </html>


    === loginScript.js ===

    $(document).ready(function(){
        $("#loginForm").submit(function(){
            var loginID = $("#userID").val();
            var loginPW = $("#password").val();

            if(loginID =='') {
                alert("아이디를 입력하세요");
                $("#userID").focus();
                return false;
            }
           
            if(loginPW =='') {
                alert("패스워드를 입력하세요!");
                $("input[type='password']").focus();
                //$("#password").focus();
                return false;
            }    
            $.post('loginChk.php',{userID:loginID, password:loginPW}, function(msg) {
                if(msg==1){ // loginChk.php 파일에서 echo 결과값
                    window.location.href = 'main.php';
                } else {
                    alert('다시 로그인 하세요');
                }
            });
            return false;
        });

        $("input[type='reset']").click(function(){
            if(!confirm("정말 입력을 취소하시겠습니까?")){
                return false;
            }
        });
    });


3. loginChk.php 파일

<?php
if(empty($_POST['userID']) || empty($_POST['password'])){
    echo 0; // 실패
} else {
    $loginID=$_POST['userID'];
    $loginPW=$_POST['password'];

    require_once 'dbconnect.php';
    require_once 'phpclass/loginClass.php';

    $c=new LoginClass();
    $row=$c->UserAuthCheck($loginID,$loginPW);
    if(is_array($row)){
        if(!isset($_SESSION)) {
               session_start();
           }
        $_SESSION['userID'] = $row['userID'];
        $_SESSION['level'] = $row['level'];
        echo 1; // 로그인 성공
    } else {
        if(!isset($_SESSION)) {
               session_start();
           }
        session_destroy();
        echo 0; // 실패
    }
}
?>


※ dbconnect.php 파일 만드는 방법은 http://link2me.tistory.com/1110 참조하라.


=== loginClass.php 파일 발췌 ===

로그인 검사는 해킹 공격적인 요소를 필터링 하기 위한 것도 고려했다.

<?php
class LoginClass {
    function UserAuthCheck($u,$p) {
        if(!isset($u) || !isset($p) || empty($u) || empty($p)) {
            return 0;
        } else {
            global $db;           
            $u = preg_replace("/[\s\t\'\;\"\=\--]+/","", $u); // 공백이나 탭 제거(사용자 실수 방지)
            $p = preg_replace("/[\s\t\'\;\"\=\--]+/","", $p); // 공백이나 탭 제거, 특수문자 제거
            // SQL injection 검사
            $u = htmlentities($u); // <script>documnet.cookie();</script> 공격 방지, 한글인식 불가
            $p = htmlentities($p); // < 를 \< 로 바꿔준다.
            $u = str_replace(array("'",""","'",'"'), array("&#39;","&quot;","&#39;","&quot;"), $u);
            if(preg_match('/[\']/',$u)) return 0; // no quotes
            if(preg_match('/[\/\\\\]/', $u)) return 0; // no slashes
            if(preg_match('/(and|null|where|limit)/i', $u)) return 0; // i는 대소문자 구별하지 말라
            if(!preg_match('/^[0-9a-zA-Z\~\!\@\#\$\%\^\&\*\(\)]{7,}$/',$p)) return 0; // 7자리이상 허용 문자만 통과
            $sql = "select * from member where pw=md5('".$p."') and id= '".$u."' ";
            if($result = mysql_query($sql,$db)) { //성공
                $row = mysql_fetch_array($result);
                if($row == NULL) return 0;
                return $row;
            } else {
                return '-1';
            }
        }
    }

}//end class LoginClass

?>


4. main.php 파일에도 HTML header, body 정보가 들어가 있다.

   메인 페이지 내용을 작성하여 원하는 데이터를 출력한다.

   DB에서 조회하여 가져온 데이터를 테이블 형식으로 보여주고자 한다면

   너무 많은 자료를 가져오면 부하문제도 생기고 화면 스크롤 문제도 생기므로

   페이징 처리를 해서 보여줘야 한다.

   http://link2me.tistory.com/1112 참조


5. 변수가 제대로 넘어오는지 체크하고자 할 경우

아래 코드를 추가하고 exit; 를 넣은 이유는 다음 코드를 실행하지 말고 중단해서 변수가 제대로 넘어오는지 여부를 한번에 확인하고자 하는 목적이다.


@extract($_POST);
var_dump($_POST);
exit;

블로그 이미지

Link2Me

,