728x90

csv 파일을 PHP를 이용하여 MySQL 에 업로드하는 예제코드다.

실전에서 활용하는 편리한 코드다.


<?php
error_reporting(0); // 경고 출력 방지, 주석처리해서 경고, 에러메시지 나오도록 하자.
require_once 'dbconnect.php';

date_default_timezone_set('Asia/Seoul');

// Edit upload location here
$tmpname    = $_FILES['file']['tmp_name'];
$realname    = $_FILES['file']['name'];

$fileExt    = getExt($realname);
$destination_path='uploads/';
$readFile = $destination_path . 'contactsdata.csv';

$errorFilename ="errorFile.txt";
$errorFile = $destination_path . $errorFilename;

$TABLENAME ='contacts'; // 테이블명

if (is_uploaded_file($tmpname)) {
    if (!strstr('[csv]',$fileExt)) {
        echo '<script type="text/javascript">alert("csv 파일만 등록할 수 있습니다.");</script>';
        exit;
    }
    move_uploaded_file($tmpname,$readFile);
    @chmod($readFile,0606);
}

/////////////////////////////////////////////////////////////////////////////////
$file_read = fopen($readFile,"r");
if(!$file_read){
    echo '<script type="text/javascript">alert("파일을 찾을 수가 없습니다!");</script>';
    echo "-2";
    exit;
}

// 파일 인코딩 모드 검사
$current_encoding = detectFileEncoding($readFile);
$total_line = 0;
$newcount = 0;
$upcount=0;
$ok = 0;

while($line = fgetcsv($file_read,1000, ";")) { // 구분자는 ; 로 지정
    // 파일 인코딩 모드 검사
    if($current_encoding != 'utf-8') {
        $line00 = iconv('euc-kr','utf-8',trim($line[0])); // 구분1(cat1)
        $line01 = iconv('euc-kr','utf-8',trim($line[1])); // 구분2(cat2)
        $line02 = iconv('euc-kr','utf-8',trim($line[3])); // officeNO
        $line03 = iconv('euc-kr','utf-8',trim($line[4])); // mobileNO
    } else {
        $line00 = trim($line[0]); // 구분1(cat1)
        $line01 = trim($line[1]); // 구분2(cat2)
        $line02 = trim($line[3]); // officeNO
        $line03 = trim($line[4]); // mobileNO
    }

    $cat1NM = $line00;
    $cat2NM = $line01;
    $officeNO = isset($line02) ? TelNumSplitRemove($line02) : '';
    $mobileNO = isset($line03) ? TelNumSplitRemove($line03) : '';

    $total_line++;
    if(strlen($mobileNO)<1) continue;

    // 구분1 코드 구하기
    $CA1= getDbData('category','name="'.$cat1NM.'" and parent_id=0','id');
    $cat1 = $CA1['id'];

    // 구분2 코드 구하기
    if(strlen($cat2NM)>0){
        $CA2= getDbData('category','parent_id="'.$cat1.'" and name="'.$cat2NM.'"','id');
        $cat2 = $CA2['id'];
    } else {
        $cat2 =0;
        continue; // 상황에 따라 체크 필요한 코드
    }

    $d_regis = date('Ymd');

    // 중복 등록 여부 검사
    $cnt = DataExistedChk($cat1,$cat2);
    if($cnt == "0"){
        $d_regis = date('Ymd');
        $QKEY = "cat1,cat2,officeNO,mobileNO";
        $QVAL = "'$cat1','$cat2','$officeNO','$mobileNO'";
        $rs = getDbInsert('contacts',$QKEY,$QVAL);
        $newcount++;
    } else {
        $QSET="officeNO='".$officeNO."',";
        $QSET.="mobileNO='".$mobileNO."'";
        $QVAL="cat1='".$cat1."' and cat2='".$cat2."' ";

        getDbUpdate('contacts',$QSET,$QVAL);
        $upcount++;
    }

    $ok ++;
    if (($ok % 500) == '0') {
        echo(" $ok 건 저장");
        flush();
        sleep(2); //500개 저장할때마다 2초씩 쉰다.
    }
} // while 문 종료
fclose($file_read);
unlink($readFile);  // 업로드 완료후에 파일 삭제 처리

$msg = '전체'.number_format($total_line).'건中 신규'.number_format($newcount).'건, 갱신'.number_format($upcount).'건 등록완료';
echo "<script type=\"text/javascript\">alert('$msg');</script>";

function getExt($filename){
    $ext = substr(strrchr($filename,"."),1);
    $ext = strtolower($ext);
    return $ext;
}

function detectFileEncoding($filepath) {
    // 리눅스 기본 기능을 활용한 파일 인코딩 검사
    $output = array();
    exec('file -i ' . $filepath, $output);
    if (isset($output[0])){
        $ex = explode('charset=', $output[0]);
        return isset($ex[1]) ? $ex[1] : null;
    }
    return null;
}

// ID Exist Check
function DataExistedChk($cat1,$cat2){
    global $db;
    $sql = "select count(*) from contacts where cat1='".$cat1."' and cat2='".$cat2."'";
    $result = mysqli_query($db,$sql);
    if($row = mysqli_fetch_row($result)){
        return $row[0];
    } else {
        return "0";
    }
}

//DB삽입
function getDbInsert($table,$key,$val){
    global $db;
    $sql ="insert into ".$table." (".$key.")values(".$val.")";
    if(mysqli_query($db,$sql)){
        return 1;
    } else {
        return 0;
    }
}

//DB업데이트
function getDbUpdate($table,$set,$where){
    global $db;
    mysqli_query($db,'set names utf8');
    mysqli_query($db,'set sql_mode=\'\'');
    $sql ="update ".$table." set ".$set.($where?' where '.getSqlFilter($where):'');
    if(mysqli_query($db,$sql)){
        return 1;
    } else {
        return 0;
    }
}

//SQL필터링
function getSqlFilter($sql)    {
    return $sql;
}


function TelNumSplitRemove($tel){
    return preg_replace("/[^0-9]/", "", $tel);    // 숫자 이외 제거
}
?>


블로그 이미지

Link2Me

,
728x90

PHP 로 jQuery 와 AJAX를 이용해서 파일을 업로드하는데 한참 삽질을 하고 적어둔다.

어쩌다 필요해서 하려고 하면 생각도 안나고 다시 제자리 걸음을 반복하는 초보자의 길을 언제나 벗어나려나 ㅠㅠ


MDB(Meterial Design Bootstrap) 기반 템플릿을 활용하여 코딩을 하느라고 class 가 이상것이 보이는 것이니 혹시라도 이 게시글을 읽으시는 분은 그냥 그런게 있나보다 하고 참조만 하시라.


파일 전송 Form 파일

<form id="uploadphoto" action="MemberPhotoUpload.php" method="post" enctype="multipart/form-data">
    <div class="card border-light mb-3" style="max-width: 30rem;">
      <div class="card-body text-dark">
        <h5 class="card-title">Image File Upload</h5>
        <input type="file" id="file" name="file" multiple />
        <input type="submit" value="Upload Photo" class="btnSubmit" />
      </div>
    </div>
</form> 

<table class='table table-responsive-sm' id='photoIDX' uid='<?php echo $idx;?>'>
    <tr><td colspan='5'>★★사진 등록시 [등록하기] , 사진 수정시 [사진을 클릭]하세요.</td></tr>
    <tr>
        <td rowspan='3'>
        <?php
            if(file_exists($imgpath)){
                echo "<img src='MemberPhotoView.php?idx=$idx&uid=$uid' width=115 height=140>";
            } else {
                echo "사진없음<br><span class='btn-floating peach-gradient photoBtn'><i class='fas fa-image'></i>등록하기</span>";
            }
        ?>
        </td>
        <th>아이디</th>
        <td><?php echo $row['userID'];?></td>
        <th>사무실번호</th>
        <td style='text-align:left;height:15px;'><?php echo $row['telNO'];?></td>
    </tr>
    <tr>
        <th>성명</th>
        <td><?php echo $row['userNM'];?></td>
        <th>휴대폰번호</th>
        <td style='text-align:left;height:15px;'><?php echo $mobileNO;?></td>
    </tr>
    <tr>
        <th>직위</th>
        <td><?php echo $chargeArr[$row['codeID']];?></td>
        <th>주업무</th>
        <td style='text-align:left;height:15px;'><?php echo $row['workrole'];?></td>
    </tr>
    <tr>
        <th>E-Mail</th>
        <td colspan='4' style='text-align:left;height:15px;'><?php echo $row['email'];?></td>
    </tr>
</table>


Script 파일

<script>

 $('.photoBtn').click(function(){
    var $obj=$(this);
    var idx=$(this).closest('#photoIDX').attr('uid');

    $('#dialog').load('MemberPhotoForm.php?idx='+idx, function() {
        $(this).dialog({
            autoOpen : true,
            height : 'auto',
            width : 'auto',
            position: { my: "center", at: "center", of: window },
            title : '사진 업로드',
            buttons : {
                "닫기" : function() {
                    $(this).dialog("close");
                }
            }
        });
        PhotoUploadChk(idx);
    });

});

function PhotoUploadChk(idx){
    $('form#uploadphoto').submit(function(e){
        e.preventDefault();
        var formData = new FormData();
        var files = $('#file')[0].files[0];
        formData.append('file',files);
        formData.append('uid',idx);

        formData.append('osType',$('select[name=osType]').val());

        var upfiles_cnt = $("input:file", this)[0].files.length;
        if(upfiles_cnt == 0){
            alert('선택된 파일이 없습니다.');
            return false;
        }

        $.ajax({
            url: 'MemberPhotoUpload.php',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            type: 'post',
            success: function (msg) {
                if(msg == 1){
                    MemberView(idx);
                } else if(msg == 0){
                    alert('form 데이터 오류인지 확인하세요.');
                } else {
                    alert('파일이 업로드되지 못했습니다.');
                }
            }
        });

    });

}
</script>


PHP 파일 업로드 관련 파일

<?php
if(isset($_POST['uid']) && $_POST['uid']>0){
    $idx=$_POST['uid'];

    $tmpname    = $_FILES['file']['tmp_name'];
    $realname    = $_FILES['file']['name'];
    $fileExt    = getExt($realname);

    $file_path='./photos/'.$idx.'.jpg';

    if (is_uploaded_file($tmpname)) {
        if (!strstr('[jpg]',$fileExt)) {
            echo "-1";
            exit;
        }
        move_uploaded_file($tmpname,$file_path);
        @chmod($file_path,0606);
        echo "1";
    }
} else {
    echo "0";
}

function getExt($filename){
    $ext = substr(strrchr($filename,"."),1);
    $ext = strtolower($ext);
    return $ext;
}
?>


파일 사이즈 검사하여 파일 사이즈를 줄이는 코드는 포함되지 않았다.


$("#uploadbutton").click(function(){
    var form = $('form')[0]; // 폼객체를 불러와서
    var formData = new FormData(form); // FormData parameter 에 담아줌
    $.ajax({
        url: 'fileupload',
        processData: false,
        contentType: false,
        data: formData,
        type: 'POST',
        success: function(result){
            alert("업로드 성공!!");
        }
    });
});

블로그 이미지

Link2Me

,