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

,