Posted
Filed under PHP

[원문] - http://hyosang.kr/tc/211


AJAX는 기본적으로 UTF-8 인코딩을 사용하기 때문에
인코딩이 euc-kr(KSC5601)인 페이지에서 ajax를 사용하게 되면 한글이 깨지게 된다.

이러한 현상을 해결하기 위해서는 통신 시 적절한 변환처리가 필요하다.

페이지에서 요청을 보낼 때
var val = encodeURIComponent("한글");
/*
값을 UTF-8 형식으로 인코딩 해 준다. "한글" 이라는 문자열은 0xED959C, 0xEAB880이므로 val에는 %ED%95%9C%EA%B8%80이라는 문자열이 들어간다.
*/

PHP에서 받을 때
$value = iconv("UTF-8", "CP949", rawurldecode($value));
/*
http://www.php.net/manual/en/function.rawurldecode.php
먼저 %로 구분된 문자열을 디코딩한다. 이것의 결과는 UTF-8 문자열이 되며,
iconv를 사용하여 euc-kr문자열로 변환하여 준다.
*/


PHP에서 페이지로 보낼때는 반대로 해 주면 된다.
PHP에서 보낼 때
$value = rawurlencode(iconv("CP949", "UTF-8", $value));

페이지에서 받을 때
val = decodeURIComponent(val);



참고로,
스크립트에서 XML노드의 텍스트를 담고 있는 속성은
IE에서는 노드.text 이지만 FF에서는 노드.textContent 이다.

2011/01/12 14:51 2011/01/12 14:51
Posted
Filed under PHP

function get_naver_map_init(mb_id,view_obj){
 var view_obj = document.getElementById(view_obj);

 var key  = get_naver_map_keycode();
 var url  = g4_path + "/util/get_naver_map_location.php";
 
 var _data = "mb_id="+mb_id + "&key=" + key;

 $.ajax({
    type:"GET",
    cache:false,
    async:true,
    url: url,
    data: _data ,
    success: function(msg){
     var point = msg.split("/");
     if(point[0] != "" &&  point[1] != "" ){
    var mapObj = new NMap(document.getElementById(view_obj),150,150);
    mapObj.setCenterAndZoom(new NPoint( point[0],point[1]),3);
     }
    }//end success
 }); //end ajax

}

2011/01/10 14:48 2011/01/10 14:48
Posted
Filed under PHP
[원문 ] - http://semtle.tistory.com/entry/PHP%EC%97%90%EC%84%9C-%EB%8B%A4%EC%A4%91%EA%B0%92CheckBox-%EC%A0%84%EC%86%A1%ED%95%98%EA%B3%A0-%ED%8E%B8%EB%A6%AC%ED%95%98%EA%B2%8C-%EB%B0%9B%EA%B8%B0

현재 페이지에서 체크박스를 여러개 만들고 선택된 값을 넘겨서 받는것은 여간 귀찮은 일이 아니다.
우선 이제까지 해오던 방식을 살펴보면..


<input type="checkbox" name="cd0" value="20">x
<input type="checkbox" name="cd1" value="30">y
<input type="checkbox" name="cd2" value="100">z


[PHP Part]

$total = ;
for($i=0;$i<3;$i++){
$amount = $_POST['cd'.$i];
$total += $amount;
}
echo $total


위와 같이 폼네임을 각각 비슷하게(하지만 똑같지는 않게)만들고 PHP부분에서 포문을 돌려 폼네임을 만들어 POST값을 받아오는, 아주 불편한 방식이었다.

이제는 최근 알아낸 기법을 살펴보면..

<form action="testcheckbox.php" method="POST" name="form1">
<p>Name :
<input type="text" name="textfield">
</p>
<p>Course:
<input type="text" name="textfield">
</p>
<p>Tel No:
<input type="text" name="textfield">
</p>
<p>
<input type="checkbox" name="cd[]" value="20">
JAVA<br>
<input type="checkbox" name="cd[]" value="30">
PERL<br>
<input type="checkbox" name="cd[]" value="10">
PYTHON<br>
<input type="checkbox" name="cd[]" value="30">
C#<br>
<input type="checkbox" name="cd[]" value="90">
JYTHON<br>
<input type="checkbox" name="cd[]" value="100">
C++<br>
<input type="checkbox" name="cd[]" value="120">
PHP</p>
<p align="center">
<input type="submit" name="Submit" value="Join Now">
</p>
<p align="left"> <br>
</p>
</form><form action="testcheckbox.php" method="POST" name="form1">
<p>Name :
<input type="text" name="textfield">
</p>
<p>Course:
<input type="text" name="textfield">
</p>
<p>Tel No:
<input type="text" name="textfield">
</p>
<p>
<input type="checkbox" name="cd[]" value="20">
JAVA<br>
<input type="checkbox" name="cd[]" value="30">
PERL<br>
<input type="checkbox" name="cd[]" value="10">
PYTHON<br>
<input type="checkbox" name="cd[]" value="30">
C#<br>
<input type="checkbox" name="cd[]" value="90">
JYTHON<br>
<input type="checkbox" name="cd[]" value="100">
C++<br>
<input type="checkbox" name="cd[]" value="120">
PHP</p>
<p align="center">
<input type="submit" name="Submit" value="Join Now">
</p>
<p align="left"> <br>
</p>
</form>

[PHP Part]

<?php
$totalprice = 0;
foreach($_POST['cd'] as $cd) $totalprice += $cd;
echo "$totalprice";
?>


폼네임을 "cd[]" 이런식으로 네임 끝에 배열 기호인 '[]' 을 붙이면, POST값으로 넘어가서는 '[]' 부분을 뺀 나머지 부분 즉 'cd' 부분이 POST의 배열의 연관배열 인덱스가 되어 참조할수 있다.
2010/12/02 11:24 2010/12/02 11:24
Posted
Filed under PHP

in_array

(PHP 4, PHP 5)

in_array값이 배열 안에 존재하는지 확인

설명

bool in_array ( mixed $needle , array $haystack [, bool $strict ] )

haystack 에서 needle 을 찾습니다.

인수

needle

찾을 값.

Note: needle 이 문자열이면, 대소문자를 구분하여 비교합니다.

haystack

배열.

strict

세번째 인수 strictTRUE로 설정하면, in_array() 함수는 haystack 안에서 needle자료형도 확인합니다.

반환값

needle 을 배열에서 찾으면 TRUE를, 아니면 FALSE를 반환합니다.

변경점

버전 설명
4.2.0 needle 이 배열일 수 있습니다.

예제

Example #1 in_array() 예제

<?php
$os
= array("Mac", "NT", "Irix", "Linux");
if (
in_array("Irix", $os)) {
    echo
"Got Irix";
}
if (
in_array("mac", $os)) {
    echo
"Got mac";
}
?>

in_array()가 대소문자를 구분하므로 두번째 조건은 실패하고, 위 프로그램은 다음을 출력합니다:

Got Irix

Example #2 in_array()에 strict 예제

<?php
$a
= array('1.10', 12.4, 1.13);

if (
in_array('12.4', $a, true)) {
    echo
"'12.4' found with strict check\n";
}

if (
in_array(1.13, $a, true)) {
    echo
"1.13 found with strict check\n";
}
?>

위 예제의 출력:

1.13 found with strict check

Example #3 in_array()에 needle로 배열

<?php
$a
= array(array('p', 'h'), array('p', 'r'), 'o');

if (
in_array(array('p', 'h'), $a)) {
    echo
"'ph' was found\n";
}

if (
in_array(array('f', 'i'), $a)) {
    echo
"'fi' was found\n";
}

if (
in_array('o', $a)) {
    echo
"'o' was found\n";
}
?>

위 예제의 출력:

  'ph' was found
  'o' was found
2010/11/08 02:43 2010/11/08 02:43
Posted
Filed under PHP
ErrorDocument 404 /404.php
2010/11/08 01:00 2010/11/08 01:00
Posted
Filed under PHP
$url = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
2010/11/07 15:08 2010/11/07 15:08
Posted
Filed under PHP
function utf8_urldecode($str) {
   
$str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str
));
    return
html_entity_decode($str,null,'UTF-8'
);;
}

2010/10/08 16:24 2010/10/08 16:24
Posted
Filed under PHP
sql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
2010/04/26 16:46 2010/04/26 16:46
Posted
Filed under PHP

[원문] - http://blog.daum.net/_blog/BlogView.do?blogid=0NClv&articleno=62&categoryId=#ajax_history_home

===========테이블 생성===========================================

CREATE TABLE userdb (

name CHAR(8),

id VARCHAR(10) NOT NULL,

email VARCHAR(40),

sex CHAR(1),

PRIMARY KEY(id)

)


INT : 정수

CHAR (M) : 문자의 수가 M개인 문자열

VARCHAR (M) : 문자의 수가 최대 M개인 문자열

TEXT : 문자의 수가 최대 65535개인 문자열



==============테이블 복사======================================

   => 테이블 복사

CREATE TABLE userdb2 AS SELECT * FROM userdb

 

=>테이블의 지정한 필드만 복사

CREATE TABLE userdb3 AS SELECT name, id FROM userdb


2010/04/09 13:07 2010/04/09 13:07
Posted
Filed under PHP
[원문] - http://codeigniter-kr.org/tip/view/236/page/3/

파일업로드를 어떻게 처리할까 하다가 좀 센스있게 보이려고 SWFUpload를 쳐다봤는데요
jQuery에도 다중업로드를 지원하는 plugin들이 많이 있길래 그중 하나를 적용해봤습니다~

uploadify(http://www.uploadify.com) 라는 플러그인인데요
다중업로드를 지원하고 파일찾기 이미지 등 다양하게 커스터마이징이 간으합니다
progress bar가 적용 되어있어서 퍼센테이지로도 보여지구요

근데 CI랑 완전 독립을 시키려고 하니 문제가 좀 있던거 같아요.. 구버전은 CI해외포럼에서 연동방법들이
다양하게 있었는데 최신버전은 적용된게 없더군요

별수없이 파일 업로드만 처리하는 파일을 따로 두고(uploadify.php) 업로드만 맞겼습니다

01.<input type="file" id="letter_banner_img" />
02.  
03.$("#letter_banner_img").uploadify({
04.        'uploader'       : '/js/uploadify/uploadify.swf', // 그냥 두시면 됩니다
05.        'script'         : '/js/uploadify/uploadify.php', // 파일업로드를 실제로 처리할 php 파일입니다.
06.        'cancelImg'      : '/js/uploadify/cancel.png', // 이것도 전 그냥 쓰구요
07.        'folder'         : '/files/letter/imgs', // 파일이 업로드될 path 정보입니다
08.        'buttonImg'      : '/img/admin/file_btn.png', // 버튼이미지는 제가 만든건데 이미비를 변경하셨다면 아래 width와 height를 이미지 크기로 잡아주셔야 합니다
09.        'width'          : 80, // 버튼이미지의 가로크기
10.        'height'         : 20, // 버튼이미지의 세로크기
11.        'wmode'          : 'transparent',
12.        'queueID'        : 'letter_img2', // 큐를 보여줄 곳을 지정합니다 div id="letter_img2" 이런식으로 해두면 그 안쪽에 큐 정보를 보여줍니다(프로그래스바)
13.        'method'         : 'post', // get, post를 모두 지원하고 default는 post랍니다
14.        'scriptAccess' : 'always'
15.        'scriptData'     : {
16.                                'tid': $('#tid').val(),
17.                                'fieldName' : 'banner_img',
18.                                'already_exists' : $("#before_banner_img").val(),
19.                                'type' : 'letter_banner'
20.                            }, // 이부분은 제가 추가로 넘겨줄 변수의 키와 값입니다.. 사용할때는 uplodify.php 파일에서 $_REQUEST['tid'] 처럼 사용됩니다
21.        'fileExt'         : '*.jpg;*.jpeg;*.png;*.gif', // 허용 확장자 목록입니다
22.        'auto'           : true, // 파일을 선택하자마자 전송을 시작합니다.. false로 해두면 기다리구요 전송시켜줄 버튼과 이벤트가 필요하게 됩니다
23.        'multi'          : false, // 여러개 파일을 업로드 하고싶을때 true로 변경하시면 됩니다
24.        onComplete         : function(event, queueID, fileObj, response, data) {
25.              
26.            $.post(
27.                "/admin/letter/upload_file_input",
28.                {
29.                    'ajax' : "true",
30.                    'file_path':obj.newTargetPath,
31.                    'file_name':obj.newName,
32.                    'tid':obj.tid,
33.                    'type':obj.type
34.                },
35.                function(data){
36.  
37.                }
38.            ); // 원래는 uplodify.php에서 해야하나, 제 실력이 미흡하여 업로드 파일을 별도로 제작했더니 ci의 편의시설을 이용하지 못하게 되서.. 넘어온 값을 다시 ajax를 사용해서 db에 업데이트 합니다;
39.             
40.        },
41.        onError: function(a, b, c, d){
42.            upload_file_error(a, b, c, d);
43.        }
44.    });

uploadify.php 파일의 내용입니다 그냥 업로드 하고 각종 필요값만 json으로 반환합니다
01.<?php
02.if (!empty($_FILES)) {
03.    $tempFile = $_FILES['Filedata']['tmp_name'];
04.    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
05.    $targetFile str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
06.      
07.    $extension = pathinfo($targetFile, PATHINFO_EXTENSION); 
08.    $new_name = $_REQUEST['fieldName']."_".$_REQUEST['tid'].".$extension";
09.    $newTargetFile str_replace('//','/',$targetPath) . $new_name;
10.      
11.    if($_REQUEST['already_exists']) unset($_REQUEST['already_exists']);
12.      
13.    move_uploaded_file($tempFile,$newTargetFile);
14.    $return['newTargetPath'] = $_REQUEST['folder'] . '/'.$new_name;
15.    $return['newName'] = $new_name;
16.    $return['tid'] = $_REQUEST['tid'];
17.    $return['type'] = $_REQUEST['type'];
18.    echo json_encode($return);
19.}
20.?>
2010/04/07 09:53 2010/04/07 09:53