'PHP 이미지 파일 존재 유무 확인'에 해당되는 글 1건

728x90

Android 코드에서 실제 파일 존재 유무를 확인하는 방법으로 했더니 Main Thread UI에서 작업을 한다고 경고 메시지가 나온다.


    private class PhotoURLExists extends AsyncTask<String, Void, Boolean> {
        @Override
        protected Boolean doInBackground(String... params) {
            try {
                HttpURLConnection.setFollowRedirects(false);
                HttpURLConnection con =  (HttpURLConnection) new URL(params[0]).openConnection();
                con.setRequestMethod("HEAD");
                return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
            }
            catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    } 


위 코드로 확인을 할 수는 있으나, 제대로 처리하는 것이 아닌거 같아서 PHP에서 자료를 가져올 때 아예 체크하는 로직으로 대체하였다.


테이블 칼럼에는 파일명이 존재하는데, 실제로는 파일이 존재하지 않을 수가 있다.

이럴 경우 Android 코드에서 파일이 존재하는 줄 알고 가져오기를 하면 에러가 발생한다.

이걸 방지하는 방법은 PHP 코드에서 파일이 폴더에 존재하는지 검사하여 없으면 공백을 반환하도록 하는 것이 좋다.


<?php
if(!isset($_SESSION)) {
    session_start();
}
// 파일을 직접 실행하면 동작되지 않도록 하기 위해서
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST"){
    @extract($_POST); // POST 전송으로 전달받은 값 처리
    if(!(isset($idx) && !empty($idx))) {
        echo 0;
        exit;
    }
    require_once 'phpclass/dbconnect.php';
    require_once 'phpclass/loginClass.php';
    $c = new LoginClass();
    $sql = "select idx,userNM,mobileNO,telNO,photo from Person";
    if(!empty($search)) {
        $where = "userNM LIKE '%".$search."%' or mobileNO LIKE '%".$search."%'";
    } else {
        $where = "";
    }

    if(strlen($where) > 0){
        $sql .= " where ".$where;
    }

    $R = array(); // 결과 담을 변수 생성
    $result = $c->putDbArray($sql);
    while($row = $result->fetch_assoc()) {
        if($row['photo'] == NULL) {
            $row['photo'] = "";
        } else {
            $path = "./photos/".$row['photo'];
            if(!file_exists($path)) {
                $row['photo'] = "";
            }
        }
        array_push($R, $row);
    }
    echo json_encode(array('result'=>$R)); //배열-문자열등을 json형식의 '문자열'로 변환
}
?>

<?php
class DBController {
    protected $db; // 변수를 선언한 클래스와 상속받은 클래스에서 참조할 수 있다.

    // 생성자
    function __construct() {
        $this->db = $this->connectDB();
        // construct 메소드는 객체가 생성(인스턴스화)될 때 자동으로 실행되는 특수한 메소드다.
    }

    // 소멸자(destructor)
    function __destruct() {
        mysqli_close($this->connectDB());
    }

    private function connectDB() {
        require_once 'dbinfo.php';
        // MySQLi 객체지향 DB 연결
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
        return $conn; // return database handler
    }
}
?>

<?php
class LoginClass extends DBController {
    // class 자식클래스 extends 부모클래스
    // override : 부모 클래스와 자식 클래스가 같은 메소드를 정의했을 경우 자식 클래스가 우선시된다.

    // 여기에 함수를 작성하면 된다.

    public function putDbArray($sql) {
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }

    public function SearchFiltering($str){
        // 해킹 공격을 대비하기 위한 코드
        $str = preg_replace("/[\s\t\'\;\"\=\-]+/","", $str); // 공백이나 탭 제거, 특수문자 제거
        return $str;
    }

}


MySQLi 객체지향 방식으로 Class를 작성해보니, 함수화하기가 쉽지 않다.
변수를 받아서 처리하는 경우가 쉽지 않다.
PDO 방식으로 하는 것은 변수처리까지 원활하게 할 수 있다.


블로그 이미지

Link2Me

,