테스트 사이트 - 개발 중인 베타 버전입니다

이미지 파일 업로드 특정 페이지에 설정하는법 질문 채택완료

하남시불빠따 4년 전 조회 2,489

게시글(view)에 파일 업로드 기능을 넣고 제출하는 버튼을 만들었습니다.

 

 

파일 업로드 기능은 1개만 할거라 write.skin.php에서  <?php for ($i=0; $is_file && $i<$file_count; $i++) { ?> 부분을 지우고 $i가 있는 부분을 다 '0'으로 줬습니다.

밑의 코드를 위 설명처럼 수정하고 view.skin.php에 넣었습니다.

 

</p>

<p><form action="<?php echo G5_BBS_URL; ?>/dashboard_update.php" method="post">

    <input type="hidden" name="wr_id" value="<?php echo $wr_id ?>">

    <div class="bo_w_flie write_div">

        <div class="file_wr write_div">

            <label for="bf_file_1" class="lb_icon"><i class="fa fa-folder-open" aria-hidden="true"></i><span class="sound_only"> 파일 #1</span></label>

            <input type="file" name="bf_file[]" id="bf_file_1" title="파일첨부 1 : 용량 <?php echo $upload_max_filesize ?> 이하만 업로드 가능" class="frm_file ">

        </div>

        <?php if ($is_file_content) { ?>

        <input type="text" name="bf_content[]" value="<?php echo ($w == 'u') ? $file[0]['bf_content'] : ''; ?>" title="파일 설명을 입력해주세요." class="full_input frm_input" size="50" placeholder="파일 설명을 입력해주세요.">

        <?php } ?></p>

<p>        <?php if($w == 'u' && $file[0]['file']) { ?>

        <span class="file_del">

            <input type="checkbox" id="bf_file_del0" name="bf_file_del[0]" value="1"> <label for="bf_file_del0"><?php echo $file[0]['source'].'('.$file[0]['size'].')';  ?> 파일 삭제</label>

        </span>

        <?php } ?>

    </div>

    <button type="submit">증거 제출하기</button>

    </form></p>

<p>

 

이제 건드려야되는 부분이 update.php 인데 파일 업로드 결과물을 뿌려줄 페이지는 제가 따로 dashboard.php 라고 만들었습니다.

그래서 view.skin.php에서 dashboard_update.php를 거쳐야하는데 

write_update.php의 파일 업로드 관련 코드를 모조리 다 긁어오기만 하면되나요??

 

밑의 코드는 write_update.php에 있는 파일관련일 것 같은 코드을 그대로 긁어온것입니다. 

수정없이 다 넣어야 되는지 모르겠네요...

게시판에서 다루는게 아니라 제가 따로 만든 bbs/dashboard.php에 담는거라 어떻게 해야할지 모르겠네요

</p>

<p>// 파일개수 체크

$file_count   = 0;

$upload_count = (isset($_FILES['bf_file']['name']) && is_array($_FILES['bf_file']['name'])) ? count($_FILES['bf_file']['name']) : 0;</p>

<p>for ($i=0; $i<$upload_count; $i++) {

    if($_FILES['bf_file']['name'][$i] && is_uploaded_file($_FILES['bf_file']['tmp_name'][$i]))

        $file_count++;

}</p>

<p>if($w == 'u') {

    $file = get_file($bo_table, $wr_id);

    if($file_count && (int)$file['count'] > $board['bo_upload_count'])

        alert('기존 파일을 삭제하신 후 첨부파일을 '.number_format($board['bo_upload_count']).'개 이하로 업로드 해주십시오.');

} else {

    if($file_count > $board['bo_upload_count'])

        alert('첨부파일을 '.number_format($board['bo_upload_count']).'개 이하로 업로드 해주십시오.');

}</p>

<p>

이건 파일개수 체크이므로 생략하고

 

</p>

<p>// 디렉토리가 없다면 생성합니다. (퍼미션도 변경하구요.)

@mkdir(G5_DATA_PATH.'/file/'.$bo_table, G5_DIR_PERMISSION);

@chmod(G5_DATA_PATH.'/file/'.$bo_table, G5_DIR_PERMISSION);</p>

<p>$chars_array = array_merge(range(0,9), range('a','z'), range('A','Z'));</p>

<p>// 가변 파일 업로드

$file_upload_msg = '';

$upload = array();</p>

<p>if(isset($_FILES['bf_file']['name']) && is_array($_FILES['bf_file']['name'])) {

    for ($i=0; $i<count($_FILES['bf_file']['name']); $i++) {

        $upload[$i]['file']     = '';

        $upload[$i]['source']   = '';

        $upload[$i]['filesize'] = 0;

        $upload[$i]['image']    = array();

        $upload[$i]['image'][0] = 0;

        $upload[$i]['image'][1] = 0;

        $upload[$i]['image'][2] = 0;

        $upload[$i]['fileurl'] = '';

        $upload[$i]['thumburl'] = '';

        $upload[$i]['storage'] = '';</p>

<p>        // 삭제에 체크가 되어있다면 파일을 삭제합니다.

        if (isset($_POST['bf_file_del'][$i]) && $_POST['bf_file_del'][$i]) {

            $upload[$i]['del_check'] = true;</p>

<p>            $row = sql_fetch(" select * from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$wr_id}' and bf_no = '{$i}' ");</p>

<p>            $delete_file = run_replace('delete_file_path', G5_DATA_PATH.'/file/'.$bo_table.'/'.str_replace('../', '', $row['bf_file']), $row);

            if( file_exists($delete_file) ){

                @unlink($delete_file);

            }

            // 썸네일삭제

            if(preg_match("/\.({$config['cf_image_extension']})$/i", $row['bf_file'])) {

                delete_board_thumbnail($bo_table, $row['bf_file']);

            }

        }

        else

            $upload[$i]['del_check'] = false;</p>

<p>        $tmp_file  = $_FILES['bf_file']['tmp_name'][$i];

        $filesize  = $_FILES['bf_file']['size'][$i];

        $filename  = $_FILES['bf_file']['name'][$i];

        $filename  = get_safe_filename($filename);</p>

<p>        // 서버에 설정된 값보다 큰파일을 업로드 한다면

        if ($filename) {

            if ($_FILES['bf_file']['error'][$i] == 1) {

                $file_upload_msg .= '\"'.$filename.'\" 파일의 용량이 서버에 설정('.$upload_max_filesize.')된 값보다 크므로 업로드 할 수 없습니다.\\n';

                continue;

            }

            else if ($_FILES['bf_file']['error'][$i] != 0) {

                $file_upload_msg .= '\"'.$filename.'\" 파일이 정상적으로 업로드 되지 않았습니다.\\n';

                continue;

            }

        }</p>

<p>        if (is_uploaded_file($tmp_file)) {

            // 관리자가 아니면서 설정한 업로드 사이즈보다 크다면 건너뜀

            if (!$is_admin && $filesize > $board['bo_upload_size']) {

                $file_upload_msg .= '\"'.$filename.'\" 파일의 용량('.number_format($filesize).' 바이트)이 게시판에 설정('.number_format($board['bo_upload_size']).' 바이트)된 값보다 크므로 업로드 하지 않습니다.\\n';

                continue;

            }</p>

<p>            //=================================================================\

            // 090714

            // 이미지나 플래시 파일에 악성코드를 심어 업로드 하는 경우를 방지

            // 에러메세지는 출력하지 않는다.

            //-----------------------------------------------------------------

            $timg = @getimagesize($tmp_file);

            // image type

            if ( preg_match("/\.({$config['cf_image_extension']})$/i", $filename) ||

                 preg_match("/\.({$config['cf_flash_extension']})$/i", $filename) ) {

                if ($timg['2'] < 1 || $timg['2'] > 16)

                    continue;

            }

            //=================================================================</p>

<p>            $upload[$i]['image'] = $timg;</p>

<p>            // 4.00.11 - 글답변에서 파일 업로드시 원글의 파일이 삭제되는 오류를 수정

            if ($w == 'u') {

                // 존재하는 파일이 있다면 삭제합니다.

                $row = sql_fetch(" select * from {$g5['board_file_table']} where bo_table = '$bo_table' and wr_id = '$wr_id' and bf_no = '$i' ");</p>

<p>                $delete_file = run_replace('delete_file_path', G5_DATA_PATH.'/file/'.$bo_table.'/'.str_replace('../', '', $row['bf_file']), $row);

                if( file_exists($delete_file) ){

                    @unlink(G5_DATA_PATH.'/file/'.$bo_table.'/'.$row['bf_file']);

                }

                // 이미지파일이면 썸네일삭제

                if(preg_match("/\.({$config['cf_image_extension']})$/i", $row['bf_file'])) {

                    delete_board_thumbnail($bo_table, $row['bf_file']);

                }

            }</p>

<p>            // 프로그램 원래 파일명

            $upload[$i]['source'] = $filename;

            $upload[$i]['filesize'] = $filesize;</p>

<p>            // 아래의 문자열이 들어간 파일은 -x 를 붙여서 웹경로를 알더라도 실행을 하지 못하도록 함

            $filename = preg_replace("/\.(php|pht|phtm|htm|cgi|pl|exe|jsp|asp|inc)/i", "$0-x", $filename);</p>

<p>            shuffle($chars_array);

            $shuffle = implode('', $chars_array);</p>

<p>            // 첨부파일 첨부시 첨부파일명에 공백이 포함되어 있으면 일부 PC에서 보이지 않거나 다운로드 되지 않는 현상이 있습니다. (길상여의 님 090925)

            $upload[$i]['file'] = abs(ip2long($_SERVER['REMOTE_ADDR'])).'_'.substr($shuffle,0,8).'_'.replace_filename($filename);</p>

<p>            $dest_file = G5_DATA_PATH.'/file/'.$bo_table.'/'.$upload[$i]['file'];</p>

<p>            // 업로드가 안된다면 에러메세지 출력하고 죽어버립니다.

            $error_code = move_uploaded_file($tmp_file, $dest_file) or die($_FILES['bf_file']['error'][$i]);</p>

<p>            // 올라간 파일의 퍼미션을 변경합니다.

            chmod($dest_file, G5_FILE_PERMISSION);</p>

<p>            $dest_file = run_replace('write_update_upload_file', $dest_file, $board, $wr_id, $w);

            $upload[$i] = run_replace('write_update_upload_array', $upload[$i], $dest_file, $board, $wr_id, $w);

        }

    }   // end for

}   // end if</p>

<p>// 나중에 테이블에 저장하는 이유는 $wr_id 값을 저장해야 하기 때문입니다.

for ($i=0; $i<count($upload); $i++)

{

    if (!get_magic_quotes_gpc()) {

        $upload[$i]['source'] = addslashes($upload[$i]['source']);

    }</p>

<p>    $row = sql_fetch(" select count(*) as cnt from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$wr_id}' and bf_no = '{$i}' ");

    if ($row['cnt'])

    {

        // 삭제에 체크가 있거나 파일이 있다면 업데이트를 합니다.

        // 그렇지 않다면 내용만 업데이트 합니다.

        if ($upload[$i]['del_check'] || $upload[$i]['file'])

        {

            $sql = " update {$g5['board_file_table']}

                        set bf_source = '{$upload[$i]['source']}',

                             bf_file = '{$upload[$i]['file']}',

                             bf_content = '{$bf_content[$i]}',

                             bf_fileurl = '{$upload[$i]['fileurl']}',

                             bf_thumburl = '{$upload[$i]['thumburl']}',

                             bf_storage = '{$upload[$i]['storage']}',

                             bf_filesize = '".(int)$upload[$i]['filesize']."',

                             bf_width = '".(int)$upload[$i]['image'][0]."',

                             bf_height = '".(int)$upload[$i]['image'][1]."',

                             bf_type = '".(int)$upload[$i]['image'][2]."',

                             bf_datetime = '".G5_TIME_YMDHIS."'

                      where bo_table = '{$bo_table}'

                                and wr_id = '{$wr_id}'

                                and bf_no = '{$i}' ";

            sql_query($sql);

        }

        else

        {

            $sql = " update {$g5['board_file_table']}

                        set bf_content = '{$bf_content[$i]}'

                        where bo_table = '{$bo_table}'

                                  and wr_id = '{$wr_id}'

                                  and bf_no = '{$i}' ";

            sql_query($sql);

        }

    }

    else

    {

        $sql = " insert into {$g5['board_file_table']}

                    set bo_table = '{$bo_table}',

                         wr_id = '{$wr_id}',

                         bf_no = '{$i}',

                         bf_source = '{$upload[$i]['source']}',

                         bf_file = '{$upload[$i]['file']}',

                         bf_content = '{$bf_content[$i]}',

                         bf_fileurl = '{$upload[$i]['fileurl']}',

                         bf_thumburl = '{$upload[$i]['thumburl']}',

                         bf_storage = '{$upload[$i]['storage']}',

                         bf_download = 0,

                         bf_filesize = '".(int)$upload[$i]['filesize']."',

                         bf_width = '".(int)$upload[$i]['image'][0]."',

                         bf_height = '".(int)$upload[$i]['image'][1]."',

                         bf_type = '".(int)$upload[$i]['image'][2]."',

                         bf_datetime = '".G5_TIME_YMDHIS."' ";

        sql_query($sql);</p>

<p>        run_event('write_update_file_insert', $bo_table, $wr_id, $upload[$i], $w);

    }

}</p>

<p>// 업로드된 파일 내용에서 가장 큰 번호를 얻어 거꾸로 확인해 가면서

// 파일 정보가 없다면 테이블의 내용을 삭제합니다.

$row = sql_fetch(" select max(bf_no) as max_bf_no from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$wr_id}' ");

for ($i=(int)$row['max_bf_no']; $i>=0; $i--)

{

    $row2 = sql_fetch(" select bf_file from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$wr_id}' and bf_no = '{$i}' ");</p>

<p>    // 정보가 있다면 빠집니다.

    if ($row2['bf_file']) break;</p>

<p>    // 그렇지 않다면 정보를 삭제합니다.

    sql_query(" delete from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$wr_id}' and bf_no = '{$i}' ");

}</p>

<p>// 파일의 개수를 게시물에 업데이트 한다.

$row = sql_fetch(" select count(*) as cnt from {$g5['board_file_table']} where bo_table = '{$bo_table}' and wr_id = '{$wr_id}' ");

sql_query(" update {$write_table} set wr_file = '{$row['cnt']}' where wr_id = '{$wr_id}' ");</p>

<p>

댓글을 작성하려면 로그인이 필요합니다.

답변 1개

채택된 답변
+20 포인트
e
4년 전

게시판 파일에 저장하는게 맞나요??

그럼, 해당 소스를 가져오면 되는건 맞는데요..

소스를 넣어보시고, 실행하면서 잘 저장되는지 확인해야 합니다.

오류나면 중간에 아래와같이 추가해서 확인해보면서 디버깅 해야 합니다.

echo 변수;

exit;

로그인 후 평가할 수 있습니다

댓글을 작성하려면 로그인이 필요합니다.

답변을 작성하려면 로그인이 필요합니다.

로그인