반응형

[1] lib설치

apt-get install libmcrypt4 php4-mcrypt

[2] 사용하면됨.

  6    echo function_exists("mcrypt_decrypt");
  7    echo function_exists("mcrypt_encrypt");


이렇게 함수를 만들어서 call해보면된다.

[3] 사용예제
For those of you that need to use PKCS#5 padding, the mcrypt API's for PHP do not support it.  However, you can DIY using the following:

<?

function encrypt_something($input
)
{
   
$size = mcrypt_get_block_size('des', 'ecb'
);
   
$input = pkcs5_pad($input, $size
);
   
   
$key = 'YOUR SECRET KEY HERE'
;
   
$td = mcrypt_module_open('des', '', 'ecb', ''
);
   
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND
);
   
mcrypt_generic_init($td, $key, $iv
);
   
$data = mcrypt_generic($td, $input
);
   
mcrypt_generic_deinit($td
);
   
mcrypt_module_close($td
);
   
$data = base64_encode($data
);
    return
$data
;
}

function
pkcs5_pad ($text, $blocksize
)
{
   
$pad = $blocksize - (strlen($text) % $blocksize
);
    return
$text . str_repeat(chr($pad), $pad
);
}

function
pkcs5_unpad($text
)
{
    $pad
= ord($text{strlen($text)-1
});
    if (
$pad > strlen($text)) return false
;
    if (
strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false
;
    return
substr($text, 0, -1 * $pad
);
}
?>

[4] 첨부파일 다운로드 [사용예제]

반응형

'Program > PHP' 카테고리의 다른 글

[ JQuery Ajax + PHP 한글 처리문제 해결방법 ]  (0) 2010.07.20
[ PHP E-mail 전송 ]  (6) 2010.07.03
PHP Excel Download Module  (21) 2010.06.22
[ PHP5 공통모듈 ]  (0) 2010.06.10
PHP - HttpRequest ( POST 방식 )  (0) 2010.06.09
반응형
자바 프로그래밍을 할때 java.lang 패키지 안의 클래스중 가~~장 많이 쓰는클래스는 무엇일까?

의심할 여지도없다.. 단연 String 문자열 클래스이다.

"그냥 단순 쓰면되지.. 머~~"  하는 그런식의 클래스처럼 보이긴 하나,, 자바에서 튜닝을 결정짓는

꽤중요한 잣데 역할을 하기도한다.

String Class에 대해 낯낯히 파해쳐 보도록 하자.

[1] String Class의 이해

말은 String Class의 이해라고 하지만 1번 절에서는 간단하게 초보 프로그래머가 실수를 범하는 간단한 사례에 대해서
설명해 보도록 하겠다.

나도 그랬지만, 대학교 jsp시간에 학교에서 가르칠때에는 String Class의 사용법을 잘못 알려주는 곳이 많다.
예를들어서 JDBC를 연결하여 DB를 조회하는 간단한 QUERY를 작성 한다고 가정하였을때, 우리는 이렇게 짠다.

String query= "SELECT "+
                    "name, id, password "+
                    " from temptable";


머 이런식으로 + 연산자를 사용해서 줄줄이 붙여나가는 식이다. 흠.~~~~

예제는 저렇게 간단하지만, 필드에 나갔을때 통계쿼리를 작성한다고 가정하면 150줄이상되는 쿼리들으 엄청많음을

유의해야한다.

그렇다면~~!

과연 저것이 정석인 것인가? ..저런 방법을 사용하게 되면 개발자 입장에서 손가락이 편할지는 모르겠지만,

시스템 입장에서는 메모리를 많이 차지 하기 때문에 전체적으로 좋지 않은 습관중 하나이다.

실질적으로 한빛 미디어에서 나온 "자바성능을 결정짓는 코딩습관" 이란 책에서 이것에 대해 메모리사용량을

PLAN을 떠놓았다.

구분 결과
메모리 사용량 10회 평균 약 5MB
응답시간 10회 평균 약 5ms
           [ 위의 query를 100회 수행하였을때 메모리 변화와 응답시간 ]

흠... 대충보면 머~~ 저정도야 하겠지만, 저건 엄청난 메모리 수치이다. 쿼리문 하나 100회 돌리는데 5M가든다고

가정하였을때,, 만약  필드에 나가 대민서비스를 한다고 생각해 보아라.그럼 분명... 서버는 메모리 부족현상이

일어날 확률이많을 것이다. 그럼 이러한 것을 고려하여 코딩하는 좋은 습관은 무엇인지 알아보자.

[2] StringBuilder / StringBuffer Class의 이해

String 관련 Class중 StringBuilder 와 StringBuffer 클래스가 존재한다. 결론부터 애기하자면 DB의 QUERY문과 같이

아주 긴~ 문자열을 이을때는 String < StringBuilder < StringBuffer 와 같은 순으로 쓰는것이좋다. 결국 StringBuffer

Class를 사용하라는 것이다.

StringBuilder 와 StringBuffer의 차이점은 크지않다. 단지 StringBuffer 클래스가 멀티스레드에 안정적이게 돌아간다는것

뿐이다. StringBuilder는 단일스레드에서 호출할때를 고려해서 만든 클래스이기 때문에 멀티스레드에서는 안정성을

보장받지 못한다. 성능상으로는 두 클래스는 큰 차이가 없다.

그럼 [1] 의 query를 StringBuilder 로 변환하였을때 메모리 사용량과 응답시간에 대해 알아보도록 하자.

StringBuilder builder = new StringBuilder()'
builder.append("SELECT");
builder.append("name, id, password ");
builder.append("from temptable");


이렇게 바꾸어보도록 하자. 아래표를 주시 해야한다.

구분 결과
메모리 사용량 10회 평균 약 371KB
응답시간 10회 평균 약 0.3ms
 [ StringBuilder를 이용하여 위 쿼리를 100번 수행했을때 결과 ]


결과를 보라 놀랍지 않은가?? 뜨~~~아...

이제 왜 장문의 긴 문자열 입력시 StringBuilder 또는 StringBuffer를 사용해야하는지 이해가 될것이다.

그럼 왜 이렇게 차이가 나는것일까? 라는 의문증이 생긴다.

[3] String클래스 와 StringBuilder / StringBuffer 클래스의 차이점.

해당 차이점에 대해 그림으로 간단히 설명해보이겠다.

[ String Class의 메모리 사용 예제 ]

100 SELECT
105 SELECT name, id, password 
110 SELECT name, id, password  from temptable


[ StringBuilder / StringBuffer의 메모리 사용예제 ]

100 SELECT
100 SELECT name, id, password 
100 SELECT name, id, password  from temptable

차이점이 보이는가?

String Class의 경우는 메번 + 연산자를 통해서 append작업시 메모리를 새로 할당하게 된다.

따라서 GC가 수행되거나 해당 프로세스가 끝나기 전까지는 메모리가 죽지 않고 살아있기 때문에 메모리를 굉장히 많이

먹는 케이스이다. 물론 매번 복사하기 때문에 수행시간역시 오래걸린다.

하지만, StringBuilder / StringBuffer 클래스는 같은 메모리번지의 공간을 할당한 다음 유동적으로 데이터를 append

하는 모습을 그림으로 볼수 있을것이다.

모두들 아하~~! 라는 생각이 들었는지 모르겠다. 결국 append하는 방법의 차이이다.

[4] Version 별로 알아보는 문자열 Class

이제 내 글을 읽은 아무개 사람들은 분명 생각할 것이다. StringBuffer 클래스만 쓰자!!! ㅋㅋ

중독증세다.. 절대 그러지마라.. JDK 1.4버젼까지만 저렇게 구동하였을뿐 , 1.5부터는 컴파일 시점에

String 클래스의 + 연산자를 StringBuffer클래스의 append 연산자로 바뀌기 때문이다.

눈으로 확인하고 싶다고???????? 1.5에서 decompile한번 해봐라~~ 그럼 확실히 소스로서 차이점을

알수 있을것이다.

[5] 결론

대망의 결론이다. 매우 좋지만, 때론 그지같은 String클래스에 대해서 알아봤다. [4] 번에서 보듯이 버젼별 차이가

있긴하지만, 필드에서 어떤버젼을 사용할지는모른다. 실제 1.4에서 경험을 많이한 나로서는 String 클래스를 쓰는데

더욱 조심하게 되었다. 결론은 이것이다.

좀 짧다 싶은 문자열은 String를 사용하고 좀 길다 싶은 문자열은 StringBuilder  /  StringBuffer 클래스를 사용하는것이.

개발자의 습관상 아주 바람직한 이상향이라고 하겠다. 아.. 벌써 새벽 1시 30분이 다되었군...

휴~~~ 새벽 1시에 잠안와서 머하는짓인지 모르겠다만,,, 내일지각하면 연차 깍이기 때문에 오타는 다음에 수정하도록

하고 잠을 자야겠다~ ㅋㅋ

그럼 모두들 공부 열심히 하세용.
반응형

'Program > JAVA' 카테고리의 다른 글

JAVA - LINUX 명령어 실행하는 방법  (0) 2010.02.06
자바 메일 강의자료 Sendmail  (0) 2010.01.27
자바 특별한 Exception  (0) 2010.01.11
Class File Version Check  (0) 2009.12.18
메모리 릭에 대해 글쓰는중 ver1  (0) 2009.11.13
반응형

매번 다시 정리해야 겠다는 마음은 먹었지만 그러지 못했다.

오늘에서야 한번 깔끔하게 정리하고 넘어가도록 하겠따.

[1] SVN 이란?
Sub Version 의 약어로 좀 비속어로 썹버젼 이러고.. ㅋㅋ 흔히들 애기하는것으로 문서 및 소스 등등의 의미있는 데이터들을 Version별로 관리할 수 있도록 지원해주는 Tool이다.

[2] SVN 접속 프로토콜은?
http,ssl, https , svn~~등등 다양한 프로토콜이 존재하지만, 가장 간단 하고 심플하게
관리할 수 있는것은 svn인것 같아서.. 이걸 기준으로 설명하도록 하겠다.

[3] SVN 설치

아래 명령어를 쳐주면된다. 반드시 sudo 권한으로 실행해야 한다.

 sudo apt-get install subversion libapache2-svn

[4] Repository 생성

아래 명령어로 Repository를 생성하면된다. 별도 메뉴얼이 없으면 File DB로 관리된다.
svnadmin create --fs-type fsfs /home/svn/project    ==> 파일 시스템 타입
svnadmin create --fs-type bdb /home/svn/project    ==> 버클리 DB 타입


[5] SVN 설정관리 폴더 구조

{SVN하위폴더}/conf/authz
=> 사용자별 , 그룹별  폴더에 대한 접근 권한을 관리한다.

{SVN하위폴더}/conf/passwd
=> 각 사용자별 userId / Password를 관리한다.

{SVN하위폴더}/conf/svnserve.conf
=> svn 저장소 의 설정파일을 셋팅한다.

[6] SVN Setting 방법

(svnserve.conf)
  1 ### This file controls the configuration of the svnserve daemon, if you
  2 ### use it to allow access to this repository.  (If you only allow
  3 ### access through http: and/or file: URLs, then this file is
  4 ### irrelevant.)
  5
  6 ### Visit
http://subversion.tigris.org/ for more information.
  7
  8 [general]
  9 ### These options control access to the repository for unauthenticated
 10 ### and authenticated users.  Valid values are "write", "read",
 11 ### and "none".  The sample settings below are the defaults.
 12 anon-access = none
 13 auth-access = write
 14 ### The password-db option controls the location of the password
 15 ### database file.  Unless you specify a path starting with a /,
 16 ### the file's location is relative to the directory containing
 17 ### this configuration file.
 18 ### If SASL is enabled (see below), this file will NOT be used.
 19 ### Uncomment the line below to use the default password file.
 20 password-db = passwd
 21 ### The authz-db option controls the location of the authorization
 22 ### rules for path-based access control.  Unless you specify a path
 23 ### starting with a /, the file's location is relative to the the
 24 ### directory containing this file.  If you don't specify an
 25 ### authz-db, no path-based access control is done.
 26 ### Uncomment the line below to use the default authorization file.
 27 authz-db = authz
 28 ### This option specifies the authentication realm of the repository.
 29 ### If two repositories have the same authentication realm, they should
 30 ### have the same password database, and vice versa.  The default realm
 31 ### is repository's uuid.
 32 # realm = My First Repository
 33
 34 [sasl]
 35 ### This option specifies whether you want to use the Cyrus SASL
 36 ### library for authentication. Default is false.
 37 ### This section will be ignored if svnserve is not built with Cyrus
 38 ### SASL support; to check, run 'svnserve --version' and look for a line
 39 ### reading 'Cyrus SASL authentication is available.'
 40 # use-sasl = true
 41 ### These options specify the desired strength of the security layer
 42 ### that you want SASL to provide. 0 means no encryption, 1 means
 43 ### integrity-checking only, values larger than 1 are correlated
 44 ### to the effective key length for encryption (e.g. 128 means 128-bit
 45 ### encryption). The values below are the defaults.
 46 # min-encryption = 0
 47 # max-encryption = 256

(passwd)
  1 ### This file is an example password file for svnserve.
  2 ### Its format is similar to that of svnserve.conf. As shown in the
  3 ### example below it contains one section labelled [users].
  4 ### The name and password for each user follow, one account per line.
  5
  6 [users]
  7 # harry = harryssecret
  8 # sally = sallyssecret
  9
 10 test = 1234

(authz)
  1 ### This file is an example authorization file for svnserve.
  2 ### Its format is identical to that of mod_authz_svn authorization
  3 ### files.
  4 ### As shown below each section defines authorizations for the path and
  5 ### (optional) repository specified by the section name.
  6 ### The authorizations follow. An authorization line can refer to:
  7 ###  - a single user,
  8 ###  - a group of users defined in a special [groups] section,
  9 ###  - an alias defined in a special [aliases] section,
 10 ###  - all authenticated users, using the '$authenticated' token,
 11 ###  - only anonymous users, using the '$anonymous' token,
 12 ###  - anyone, using the '*' wildcard.
 13 ###
 14 ### A match can be inverted by prefixing the rule with '~'. Rules can
 15 ### grant read ('r') access, read-write ('rw') access, or no access
 16 ### ('').
 17
 18 [aliases]
 19 # joe = /C=XZ/ST=Dessert/L=Snake City/O=Snake Oil, Ltd./OU=Research Institute/CN=Joe Average
 20
 21 [groups]
 22 # harry_and_sally = harry,sally
 23 # harry_sally_and_joe = harry,sally,&joe
 24 [/]
 25 test = rw
 26
 27 [/home/svn/session1]
 28
 29 test = rw

[ SVN 서버 재구동방법 ]

(서버 시작)
 $ sudo killall svnserve


(서버 종료)
$ sudo svnserve -d -r /home/svn/

반응형
반응형
1. 문자열 깨진것 삭제법

find  . ! -maxdepth 1  -regex '^.*' -exec rm -i {} \;
반응형

'Server > Linux' 카테고리의 다른 글

NCFTP 사용법 설명  (0) 2010.04.25
VIMRC 파일 설정방법  (0) 2010.01.29
Ubuntu SVN 설치 / 운영  (0) 2010.01.19
Ubuntu locale 설정 바꾸기  (0) 2010.01.18
Strandard Input / Output / Error 정의와 의미  (4) 2010.01.16

+ Recent posts