Sep 102012
 

예전에는 HTML 작업이 단순했지만, jQuery, Ajax등을 사용하면서 복잡한 Javascript을 많이 사용하게 되었습니다. 개발을 하게 되면 무엇보다 개발환경을 잘 파악해서 활용하는 것이 중요합니다.

대부분 작업을 Chrome에서 작업을 하면서 debug를 하지만, 브라우저 호환성을 위해서 IE에서 확인을 해야 합니다. 하지만 IE에서 debug 를 사용하게 되면 자주 응답없음 이라는 문구를 만나면서 debug를 하기 힘든 상황이 많이 발생합니다.
이런 경우에는 어쩔수 없이 원시적으로 alert() 혹은 log를 출력해서 확인을 해야 합니다.

하지만 IE에서 console.log를 사용하게 되면 오류가 발생하기 때문에 아래와 같은 방법을 사용하면 됩니다.

확인을 하고자 하는 페이지에서 F12을 눌러서 개발자 도구를 실행합니다. 그리고 스크립트 탭을 선택을 한 다음에 페이지를 재로딩을 하게 되면 console.log 를 사용할수 있으며, 해당 로그가 콘솔에 출력되는 것을 확인할 수 있습니다.

그리고 오류를 방지하기 위해서 아래와 같은 코드로 출력을 하게 되면 개발자도구가 비활성화 되었을때에도 오류를 발생시키지 않게 된다.

 
    if(typeof console != 'undefined') { console.log("debug message"); }

참고 URL : http://stackoverflow.com/questions/690251/what-happened-to-console-log-in-ie8

Print Friendly
Sep 062012
 

웹 페이지에서 서버로 부터 빠른 데이타를 수신하기 위해서 AJAX(Asynchronous JavaScript and XML)가 아닌 JSON(JavaScript Object Notation)을 많이 사용하게 된다.
보안에 문제가 발생할수도 있지만, 동일 도메인이 아닌 다른 서버로 부터 JSON 데이타를 빠르게 수신해서 처리하는 경우에 JSONP(JSON with padding)를 사용하면, 1개의 데이타를 다양한 웹서비스에서 활용이 가능하다.

원리는 아래와 같이 HTML에서 head에 JavaScript를 append 해서 해당 배열을 가져와서 처리하는 방식으로 처리를 한다.

이렇게 하면 문제는 동기화 방식으로 동작을 하기 때문에 순차적으로 데이타를 전달받게 되므로, 아래의 소스와 같이 재요청시 기존에 동작중인 쿼리를 모두 취소를 해버리면 비동기 방식의 데이타 수신이 가능하다.

데이타는 queue를 만들어서 데이타를 순차적으로 처리를 하면 하지만, 간혹 queue에 빠졌지만, callback이 여러번 발생될 경우도 있다. 이런 경우만 callback 함수에서 추가 처리만 해주면 다양한 브라우저에서 사용이 가능한 JSONP 라이브러리가 완성이 된다.

Sencha 로 프로젝트를 진행하다가 처음에 그냥 웹에 있는 소스를 참고해서 사용하다가 원하는 대로 동작을 하지 않아서 소스를 파악하고, 처리 방식을 나름대로 제정리를 해봤습니다.

참조URL: http://www.tomdupont.net/2010/12/extuxjsonp-v20.html

 
Ext.ns('Ext.ux');
Ext.ux.JSONP = (function () {
        var _queue = [];
        var _clearQueue = function () {
                if(_queue.length==0) { return; }
 
                while(_queue.length) {
                        var _current = _queue.shift();
 
                        try {
                                document.getElementsByTagName('head')[0].removeChild(_current.script);
                        } catch(err) { ; }
                }
        };
        var _lastCallback;
 
        return {
                request: function (url, o) {
                        if (!url) { return; }
 
                        o.params = o.params || {};
                        if (o.callbackKey)
                                o.params[o.callbackKey] = 'Ext.ux.JSONP.callback';
 
                        var params = Ext.urlEncode(o.params);
                        var script = document.createElement('script');
                        script.type = 'text/javascript';
                        script.charset = 'utf-8';
                        script.src = url + '?' + params;
 
                        _lastCallback = o.callback;
 
                        _clearQueue();
                        _queue.push({
                                url: url,
                                script: script,
                                callback: o.callback || function () { },
                                scope: o.scope || window,
                                params: params || null
                        });
 
                        document.getElementsByTagName('head')[0].appendChild(script);
                },
                callback: function (json) {
                        var _current = _queue.shift();
                        if (_current == null) {
                                _lastCallback.apply(window, [json]);
                                return;
                        }
 
                        try {
                                document.getElementsByTagName('head')[0].removeChild(_current.script);
                        } catch(err) { ; }
 
                        _current.callback.apply(_current.scope, [json]);
                }
        }
})();

팁으로 한글 Internet Explorer 9 에서 가끔 JavaScript를 로딩할때 배열에 있는 한글이 깨지는 경우가 발생한다.
이러한 문제를 해결하기 위해서 charset 을 꼭 선언하여 사용하는 것이 효과적이다.

Print Friendly
Sep 042012
 

MySQL에서 사용하는 패스워드로 사용할 수 있는 함수를 버전별로 테스트한 결과입니다.

프로그램을 시작할때 참고를 해서 테스트를 해보시면 좋습니다.

비밀번호를 md5()를 한 다음에 sha1()을 처리하고, 나머지 데이타는 encode() 혹은 des_encrypt()를 내부 암호키를 이용해서 저장하고 관리하는 방법을 사용하면 효과적입니다.

[smlee@A ~]$ mysql -p -u root
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 644167
Server version: 5.0.77 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> select password('dltjrans');
+----------------------+
| password('dltjrans') |
+----------------------+
| 337c52a05f635196     |
+----------------------+
1 row in set (0.03 sec)

mysql> select sha1('dltjrans');
+------------------------------------------+
| sha1('dltjrans')                         |
+------------------------------------------+
| 2734580af3645aae53a80ce3a60841636e4f5f16 |
+------------------------------------------+
1 row in set (0.02 sec)

mysql> select sha2('dltjrans');
ERROR 1305 (42000): FUNCTION sha2 does not exist

mysql> select encrypt('dltjrans');
+---------------------+
| encrypt('dltjrans') |
+---------------------+
| iBlePNVyWUPF2       |
+---------------------+
1 row in set (0.00 sec)

mysql> select md5('dltjrans');
+----------------------------------+
| md5('dltjrans')                  |
+----------------------------------+
| 44022b75cd0626a239a1c0ec42e0b902 |
+----------------------------------+
1 row in set (0.00 sec)

mysql> select old_password('dltjrans');
+--------------------------+
| old_password('dltjrans') |
+--------------------------+
| 337c52a05f635196         |
+--------------------------+
1 row in set (0.00 sec)

mysql> show variables;
+---------------------------------+------------------------------------------------------------+
| Variable_name                   | Value                                                      |
+---------------------------------+------------------------------------------------------------+
......
| old_passwords                   | ON                                                         |
......
+---------------------------------+------------------------------------------------------------+
239 rows in set (0.01 sec)

[smlee@B ~]$ /usr/local/mysql/bin/mysql --character-sets-dir=utf8  -p -u root
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 326943
Server version: 5.1.58-log Source distribution

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select password('dltjrans');
+-------------------------------------------+
| password('dltjrans')                      |
+-------------------------------------------+
| *8FE4DE9DB3E99B3D33C46101724499112B4E08C0 |
+-------------------------------------------+
1 row in set (0.00 sec)

mysql> select sha('dltjrans');
+------------------------------------------+
| sha('dltjrans')                          |
+------------------------------------------+
| 2734580af3645aae53a80ce3a60841636e4f5f16 |
+------------------------------------------+
1 row in set (0.00 sec)

mysql> select sha1('dltjrans');
+------------------------------------------+
| sha1('dltjrans')                         |
+------------------------------------------+
| 2734580af3645aae53a80ce3a60841636e4f5f16 |
+------------------------------------------+
1 row in set (0.00 sec)

mysql> select encrypt('dltjrans');
+---------------------+
| encrypt('dltjrans') |
+---------------------+
| dZew2kBw.Cajg       |
+---------------------+
1 row in set (0.00 sec)

mysql> select old_password('dltjrans');
+--------------------------+
| old_password('dltjrans') |
+--------------------------+
| 337c52a05f635196         |
+--------------------------+
1 row in set (0.00 sec)

[smlee@C ~]$ mysql -p -u root
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 33751
Server version: 5.5.21 MySQL Community Server (GPL)

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select password('dltjrans');
+-------------------------------------------+
| password('dltjrans')                      |
+-------------------------------------------+
| *8FE4DE9DB3E99B3D33C46101724499112B4E08C0 |
+-------------------------------------------+
1 row in set (0.00 sec)

mysql> select sha('dltjrans');
+------------------------------------------+
| sha('dltjrans')                          |
+------------------------------------------+
| 2734580af3645aae53a80ce3a60841636e4f5f16 |
+------------------------------------------+
1 row in set (0.03 sec)

mysql> select sha1('dltjrans');
+------------------------------------------+
| sha1('dltjrans')                         |
+------------------------------------------+
| 2734580af3645aae53a80ce3a60841636e4f5f16 |
+------------------------------------------+
1 row in set (0.00 sec)

mysql> select encrypt('dltjrans');
+---------------------+
| encrypt('dltjrans') |
+---------------------+
| yb/DPswDxmSnk       |
+---------------------+
1 row in set (0.00 sec)

mysql> select old_password('dltjrans');
+--------------------------+
| old_password('dltjrans') |
+--------------------------+
| 337c52a05f635196         |
+--------------------------+
1 row in set (0.00 sec)

mysql>
Print Friendly
Sep 042012
 

DB에서 가능하면 join을 사용하지 않도록 설계를 하면 성능에 많은 도움이 된다.

하지만 어쩔수 없는 경우에는 outer join을 사용하면 빠른 속도로 join이 가능하다.

그래서 left outer join을 자주 사용하게 되는데. 이런 경우 join이 되는 테이블의 데이타가 없는 경우에도 결과값은 생성이 되게 된다.

이런 경우에 join이 되는 테이블의 데이타가 없는 경우에는 아래와 같이 판별이 가능한다.
(MySQL 메뉴얼에서 참고한 내용)

If there is a row in A that matches the WHERE clause, but there is no row in B that matches the ON condition, an extra B row is generated with all columns set to NULL.

실제로 2개의 테이블이 느슨한 연결 상태라서 foreign key가 없는 row가 존재할 수 있다.
아래와 같은 쿼리를 통해서 확인하고, delete 처리가 가능하다.

SELECT *
FROM tb_abc a
LEFT JOIN tb_123 b ON a.title = b.title
WHERE a.TYPE = 'ok'
AND b.STATUS IS NULL

참고 URL : http://dev.mysql.com/doc/refman/5.5/en/left-join-optimization.html

Print Friendly
Sep 042012
 

php에서 time() 을 호출하게 되면 unix timestamp를 반환하게 된다. 해당 값은 단위가 초이기 때문에 간단한 수칙연산으로 날짜를 변경이 가능하다.

하지만, 현재 시간에서 1달을 더하거나 할때에는 생각할 부분이 많다. 30 혹은 31일인 경우까지 고려를 해야 하며, 1년을 더 할 경우에는 윤년 계산까지 해야 한다.

이럴때 아래의 strtotime() 를 사용하면 보다 간편하게 계산이 가능하다.

 
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>

참고 URL: http://www.php.net/manual/en/function.strtotime.php
참고 URL: http://www.php.net/manual/en/function.time.php

Print Friendly
Plugin from the creators of Brindes :: More at Plulz Wordpress Plugins