CI 코드

제목 [예제] 폼검증 파일업로드 동시사용
글쓴이 ci세상 작성시각 2009/09/02 14:53:16
댓글 : 6 추천 : 0 스크랩 : 0 조회수 : 20672   RSS

용도 :  폼검증과 파일업로드를 동시에 사용했을때 예제코드입니다.

폼검증 : http://codeigniter-kr.org/user_guide/libraries/form_validation.html
파일업로드 : http://codeigniter-kr.org/user_guide/libraries/file_uploading.html


#### 폴더생성 ###

루트 디렉토리에 uploads 폴더를 생성후 퍼미션을 777로 만듭니다.


#### 컨트롤러 ###
<?php

class Welcome extends Controller {

	function Welcome()
	{
		parent::Controller();	
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
	}
	
	function index()
	{
		$config['upload_path'] = './uploads/';
		$config['allowed_types'] = 'zip|gif|jpg|png';
		$config['max_size']	= '20000';
		$config['max_width']  = '1024';
		$config['max_height']  = '768';
		
		
		$this->load->library('upload', $config);
		$this->form_validation->set_rules('name', '이름을', 'required');
		
		
	
        if($this->form_validation->run() == false || ! $this->upload->do_upload())
        {
        	
       	$this->load->view('welcome_message');  
        }
        else
        {
				
			$data = array('upload_data' => $this->upload->data());
			// 디비처리
			redirect('success.php');	        	
        				
        }	
        
	}

}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */

### 뷰파일 ###

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Upload Form</title>

</head>
<body>

<?php echo $this->upload->display_errors();?>
<?php echo validation_errors (); ?> 

<?php echo form_open_multipart('');?>
이름 : <input type="text" name="name" size="20" value="<?php echo set_value('name');?>">
첨부 : <input type="file" name="userfile" size="20" />

<br /><br />

<input type="submit" value="upload" />

</form>

</body>
</html>

####### 참조사항 : 폼검증에서 첨부파일 체크하기 - 라이브러리 대체 #############

케이든님이 알려주신 사이트 주소가 언제 사라질지 몰라서 파일첨부해 두니 참조하시기 바랍니다.^^
에러메세지만 한글로 살짝 변경했습니다.~~

####### 사용시 주의사항 #########

1. gif, jpg, png 와 기타 확장자를 동시에 사용시 gif 앞으로 배치를 해야 합니다.
$config['allowed_types'] = 'gif|jpg|png|zip';
zip 파일 업로드 됨
$config['allowed_types'] = 'zip|gif|jpg|png';

2. 업로드 에러메세지는 일반 폼검증이 한개 이상 존재할때만 출력이 됩니다. (2009년 11월 20일 추가)

$this->form_validation->set_rules('name', '이름을', 'required'); // 이것이 꼭! 한개 이상 존재해야 함



첨부파일 vali.zip (6.7 KB)
 다음글 [팁] 동적스크립트 dynamic 연동 (3)
 이전글 [팁] xml php4, php5 버젼대 사용예 (5)

댓글

케이든 / 2009/09/02 15:11:28 / 추천 0
emc / 2009/09/02 16:22:23 / 추천 0
//케이든
우와 좋네요.

//ci세상
1. 에러메시지는 원래 초기에 뿌려지지 않는게 정상아닌가요?

ci세상 / 2009/09/02 16:54:03 / 추천 0
에러는 처음부터 뿌려지면 안되구요 서브밋 했을때 보여져야 합니다.^^
케이든님이 알려주신 나만의 라이브러리 확장은 저도 사용중인데 80% 만족합니다.^^

<대체소스 특징>
1.  이소스는 form_open_multipart 폼헬퍼 사용시 파일이름 체크할때 아주 유용하게 사용이 가능합니다.
2.  파일이름 체크도 기본적으로 Form_validation에서 체크를 해주어야 하는데 안해준것이 문제가 되었습니다.
3.  위의 소스가 링크가 되어 있어서 사라질 위험성이 있으니 해당글에 첨부해 두겠습니다.


<제가 이글을 올린 목적중>
 폼검증에 기본적으로 첨부파일은 체크가 되도록 지원이 되어야 한다는 부분이었습니다.^^

SVN 최신버젼은 될런지 아직 검토는 안해보았습니다.~
변종원(웅파) / 2009/09/03 15:54:17 / 추천 0
흠.. 좋네요. 전에 2% 부족했던걸 채워주네요.
루디아 / 2009/10/15 17:42:22 / 추천 0

음.. 여기 있는걸 따라서 했는데.. 자료가 안올라가네요.
참고로 저는 codeigniter 1.7.1 match box를 사용하고 있습니다.
 // upload test start   
    $config['upload_path'] = './uploads/';
      $config['allowed_types'] = 'gif|jpg|png';
      $config['max_size'] = '100';
     $config['max_width']  = '1024';
      $config['max_height']  = '768';
 
     $this->load->library('upload', $config);
 
    if (!$this->upload->do_upload())
      {
        $error = array('error' => $this->upload->display_errors());      
      }
      else
      {
        $data = array('upload_data' => $this->upload->data());       
      }
   // upload test end 

단지.. 저는 upload test 뒤에 db check 를 넣었습니다.

function confirm() {

// upload check

// form vaildation check

}

 

ci세상 / 2009/10/15 22:25:18 / 추천 0
gif, jpg, png 다 안올라가나요? 다음처럼 다시한번 해보세요 ..

$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'zip|gif|jpg|png';
$config['max_size']	= '20000';
$config['max_width']  = '1024';
$config['max_height']  = '768';

윈도우가 아니고 리눅스 환경이라면 uploads 폴더의 퍼미션을 777로 해주세요..