PHP

 

 

CREATE TABLE imgblob (
  image_id tinyint(3) NOT NULL AUTO_INCREMENT,
  image_type varchar(25) NOT NULL,
  image longblob NOT NULL,
  image_size varchar(255) NOT NULL,
  image_name varchar(50) NOT NULL,
  KEY image_id (image_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

 

upload-image.html

<!DOCTYPE html>

<html>
<head><title>File Upload To Database</title></head>
<body>
<h2>Please Choose a File and click Submit</h2>
<form enctype="multipart/form-data" action="uploadImage.php" method="post">
    <div><input name="userfile" type="file"/></div>
    <div><input type="submit" value="Submit"/></div>
</form>

</body>
</html>

 

img_fileUpload_process.php

<?php
include_once ("../lib/db_connect.php");
$connect = dbconn();

if (! isset($_FILES['userfile'])) {
    echo '<p>파일을 선택하세요</p>';
}else{
    
    /*******************  업로드 파일 검수   시작  ********************/
    $member=member();  //회원정보
    if(!isset($member['user_id'])){
        myAlert("로그인 후 이용가능합니다.", "../login.php");
        exit();
    }    
        
    $allowed_ext = array('jpg','jpeg','png','gif');
    
    // 변수 정리
    $error = $_FILES['userfile']['error'];
    $name = $_FILES['userfile']['name'];
    $ext = explode('.',$name);
    $ext = strtolower(array_pop($ext));
    
    $type=$_FILES['userfile']['type'];
    $fileSize=$_FILES['userfile']['size'];    
    $fileLimit=$_POST['fileLimit'];
    
    
    if($fileLimit!="all"){    //파일 업로드 제한 없을경우
        // 1MB = 1024 (KB);
        // 1KB = 1024 (byte);
        $filePermitSize=(int)$fileLimit * 1024* 1024; //50MB
        if($fileSize >$filePermitSize){
            myAlert("파일 용량이 초과 되었습니다.", "../imgUpload.php");
            exit;
        }
        $fileLimit = $fileLimit." MB";
    }else{
        $fileLimit= "없음";
    }
    
    // 오류 확인
    if( $error != UPLOAD_ERR_OK ) {
        switch( $error ) {
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                myAlert("파일이 너무 큽니다.", "../imgUpload.php");
                break;
            case UPLOAD_ERR_NO_FILE:
                myAlert("파일이 첨부되지 않았습니다.", "../imgUpload.php");
                break;
            default:
                myAlert("파일이 제대로 업로드되지 않았습니다.", "../imgUpload.php");
        }
        exit;
    }
    
     //확장자 확인
    if( !in_array($ext, $allowed_ext) ) {
        myAlert("허용되지 않는 확장자입니다.", "../imgUpload.php");
        exit;
    }
    /********************* 업로드 파일 검수  끝  *********************/
    
    
    
    
    
    try {
        upload();       
        echo '<p><img src="data:image/bmp;base64,' . base64_encode(getImage(null, pdoConn())) . '"  width="200" /></p>';        
        echo '<p>업로드 처리 되었습니다.</p>';
        echo '<p><a href="../imgUpload.php">이미지 파일을 TEXT 형태로 저장</a></p>';
    } catch (Exception $e) {
        echo '<h4>' . $e->getMessage() . '</h4>';
    }
}

function upload(){

    if (is_uploaded_file($_FILES['userfile']['tmp_name']) && getimagesize($_FILES['userfile']['tmp_name']) != false) {
        
        /** 이미지 정보를 얻습니다 */        
        $size = getimagesize($_FILES['userfile']['tmp_name']);

        /**  * * 변수 할당**   */
        $type = $size['mime'];
        $imgfp = fopen($_FILES['userfile']['tmp_name'], 'rb');
        $size = $size[3];
        $name = $_FILES['userfile']['name'];
        $maxsize = 99999999;

        /**  * * 파일이 최대 파일 크기보다 작은지 확인 **    */
        if ($_FILES['userfile']['size'] < $maxsize) {
            
            /**  * * DB에 연결**  */
            // $dbh = new PDO("mysql:host=127.0.0.1;dbname=testdb", 'root', 'root-password');

            /** *오류 모드 설정 **  */
            $dbh = pdoConn();
            $stmt = $dbh->prepare("INSERT INTO imgblob (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");

            /**  매개변수를 바인딩 **/
            $stmt->bindParam(1, $type);
            $stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
            $stmt->bindParam(3, $size);
            $stmt->bindParam(4, $name);
        
            $stmt->execute();
         
        } else {
            throw new Exception("파일 크기 에러");
        }
    }else{
        // 파일이 허용된 최대값보다 작지 않으면 오류.
        throw new Exception("지원되지 않는 이미지 형식!");
    }   
    
}

?>

 

 

 

 

 

 

기타

db_connect.php

<?php
//에러 출력
error_reporting(E_ALL);
ini_set("display_errors", 1);

if ((function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
	session_start();//세션 시작
}
		 
function dbconn(){
	$host_name="localhost"; //호스트네임
	$db_user_id="pro5";     //DB 
	$db_name="pro5";        //DB아이디
	$db_pw="pro5";         //DB비번	
	//mysqli_connect([아이피], [아이디], [비밀번호], [DB명], [포트]);
	$connect = mysqli_connect($host_name,$db_user_id,$db_pw, $db_name,'3306') or die("연결에 실패 하였습니다....");
	return $connect;
}

function pdoConn(){
    $host_name="localhost"; //호스트네임
    $db_user_id="pro5";     //DB 
    $db_name="pro5";        //DB아이디
    $db_pw="pro5";         //DB비번	
    //$dbh = new PDO("mysql:host=127.0.0.1;dbname=test_db", 'root', 'root-password');
    $dbh = new PDO("mysql:host=localhost;dbname=".$db_name, $db_user_id, $db_pw);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    return $dbh;
}




function myAlert($msg , $href){
    echo '<script>
	alert("'.$msg.'");
    location.href="'.$href.'";
	</script>';
    exit;
}


//암호화 
function myEncrypted($key, $param){
  
    // 256 bit 키를 만들기 위해서 비밀번호를 해시해서 첫 32바이트를 사용합니다.
    $key = substr(hash('sha256', $key, true), 0, 32);
    
    // Initial Vector(IV)는 128 bit(16 byte)입니다.
    $iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
    // 암호화
    
    $encrypted = base64_encode(openssl_encrypt($param, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv));
    return $encrypted;   
}

//복호화
function myDecrypted($key, $encrypted){
    
    // 256 bit 키를 만들기 위해서 비밀번호를 해시해서 첫 32바이트를 사용합니다.
    $key = substr(hash('sha256', $key, true), 0, 32);
    
    // Initial Vector(IV)는 128 bit(16 byte)입니다.
    $iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);

    $decrypted = openssl_decrypt(base64_decode($encrypted), 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);   
    return $decrypted;
}


//로그인 회원 세션 정보
function member(){
	global $connect;	
	$member="";
	if(isset($_SESSION["member"])){
		$member =$_SESSION["member"];	
	}	 
	return $member;
}



function getImage($image_id, $pdoConn){
    
    try {
        /*** 데이터베이스에 연결 ***/
        $dbh = $pdoConn;
        
        /*** PDO 오류 모드를 예외로 설정 ***/
        // $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $sql="";
        /*** SQL 문***/
        if($image_id==null){
            $sql = "SELECT image, image_type FROM imgblob ORDER BY image_id  DESC LIMIT 1 ";
        }else{
            $sql = "SELECT image, image_type FROM imgblob WHERE image_id=$image_id";
        }
        
        /*** SQL 준비  ***/
        $stmt = $dbh->prepare($sql);
        
        /*** 쿼리를 실행 ***/
        $stmt->execute();
        
        /*** 페치 모드를 연관 arra로 설정 ***/
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        
        /*** 이미지의 헤더를 설정 ***/
        $array = $stmt->fetch();
        
        /*** 단일 이미지와 유형이 있는지 확인  ***/
        if(sizeof($array) == 2)
        {
            /*** 헤더를 설정하고 이미지를 표시 ***/
           // header("Content-type: ".$array['image_type']);            
            return    $array['image'];                        
        }
        else{
            throw new Exception("Out of bounds Error");
        }
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }catch(Exception $e){
        echo $e->getMessage();
    }
}


?>

 

 

업로드 된 이미지 목록 불러오기

<?php
include_once ("../lib/db_connect.php");
$conn = dbconn();
$sql = "select * from imgblob";
$result = mysqli_query($conn, $sql);

$count=0;
echo  "<a href='index.php'>홈</a>"; 
while ($row = mysqli_fetch_array($result)) {
    $count++;
    echo '<p><img src="data:image/bmp;base64,' . base64_encode($row['image']) . '"  width="200" /></p>';
}

if($count==0){
    echo  "<p>등록된 데이터가 없습니다.</p>";
}

?>

 

 

 

 

참조 :https://salix97.tistory.com/181

 

about author

PHRASE

Level 60  라이트

대문 밖이 저승이라 , 사람은 언제 죽을지 모른다는 말.

댓글 ( 4)

댓글 남기기

작성