Programming/PHP2018. 2. 20. 19:56

PHP에서 Root 권한 계정으로 AD(Active Directory) 비밀번호 변경시 

AD의 이전 비밀번호 재사용 금지 정책 적용


<?php function getPassword($sPassword) { $sPassword = '"' . $sPassword . '"'; $nCount = strlen($sPassword); $sNewPassword = ""; for ($i = 0; $i < $nCount; $i++) { $sNewPassword .= $sPassword[$i] . "\000"; } return $sNewPassword; } $ctrl2012 = array( // LDAP_SERVER_POLICY_HINTS_OID for Windows 2012 and above "oid" => "1.2.840.113556.1.4.2239", "value" => sprintf("%c%c%c%c%c", 48, 3, 2, 1, 1) ); $ctrl2008 = array( // LDAP_SERVER_POLICY_HINTS_DEPRECATED_OID for Windows 2008 R2 SP1 and above "oid" => "1.2.840.113556.1.4.2066", "value" => sprintf("%c%c%c%c%c", 48, 3, 2, 1, 1) ); /****** ** 윈도우 2012이상의 경우 $ctrl2012 사용 ** 윈도우 2008의 경우 $ctrl2008 사용 *******/ if (!ldap_set_option($ldap_connection, LDAP_OPT_SERVER_CONTROLS, array($ctrl2008))) { echo "ERROR: Failed to set server controls"; } $userdata["unicodePwd"] = getPassword('newPassword'); $result = ldap_mod_replace($ldap_connection, $dn , $userdata); if (!$result) { echo "\nErrorNo : ".@ldap_errno($ldap_connection); echo "\nErrorMsg : ".@ldap_error($ldap_connection); }else{ echo 'OK'; } ?>


참고 해외 블로그 : http://laviefrugale.blogspot.kr/2013/01/enforcing-active-directory-password.html

MS  참고 자료 : https://msdn.microsoft.com/en-us/library/cc223320.aspx

Posted by 시니^^
Programming/PHP2015. 6. 10. 17:01

프로시져 내부에 SELECT 구문이 여러개 있어서 output row을 여러개 받아야 할 경우 예시


1. 프로시져 ( MSSQL 기준 작성함...)

CREATE PROCEDURE [dbo].[spTest]
AS
BEGIN
SELECT TOP 2 log_id FROM testLog ;
SELECT TOP 2 log_id FROM testLog ;
END


2. PHP 코드

<?php
  $stmt = $conn->prepare("exec spTest");
  $stmt->execute();
  $results = array();
  do {
    $results[] = $stmt->fetchAll();
  }while ($stmt->nextRowset());
  print_r($results);
?>


3. 결과셋

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [log_id] => 1
                    [0] => 1
                )
           [1] => Array
                (
                    [log_id] => 2
                    [0] => 2
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [log_id] => 1
                    [0] => 1
                )
            [1] => Array
                (
                    [log_id] => 2
                    [0] => 2
                )
        )
)


※ 위에 예시는 거의 사용할 일이 크게 없었으며....

   아래 참고사이트에 보면 나오듯이... 게시물에 total값 별도로 output 이나 리턴 받고.. 

   요청하는 범위에 게시물의 row 수를 받을때 사용하는 일이 더 많은 듯하다....


참고사이트 

http://trentrichardson.com/2011/08/10/making-sense-of-stored-procedures-with-php-pdo-and-sqlsrv/

http://www.joeyrivera.com/2009/using-mysql-stored-procedure-inout-and-recordset-w-php/

Posted by 시니^^
Programming/PHP2014. 9. 18. 14:49

Github 주소

https://github.com/msgpack/msgpack-php


소스설치방법

$ wget https://github.com/msgpack/msgpack-php/zipball/master -O msgpack-php.zip
$ unzip msgpack-php.zip 
$ cd msgpack-msgpack-php-da24be3/
$ phpize
Configuring for:
PHP Api Version:         20121113
Zend Module Api No:      20121212
Zend Extension Api No:   220121212

$ ./configure
$ make && make install
Installing shared extensions:     /usr/lib64/php/modules/
Installing header files:          /usr/include/php/


$ cd /usr/lib64/php/modules/
$ ll | grep msgpack
-rwxr-xr-x 1 root root  388516 Sep 18 14:27 msgpack.so


##### php.conf 디렉토리에 맞게 ini 에 extension 등록하기! 안되면 php.ini등록해도됨
$ echo extension=msgpack.so > /etc/php.d/msgpack.ini 

##### 웹서버종류에 따라서 Apache Restart 또는 php-fpm restart
$ /etc/init.d/php-fpm restart

##### 최종확인
$ php -i | grep 'MessagePack Support'
MessagePack Support => enabled

<?php phpinfo() ?> 
MessagePack Support enabled
Session Support enabled
extension Version   0.5.6-dev
header Version  0.5.4
Directive   Local Value Master Value
msgpack.error_display   On  On
msgpack.illegal_key_insert  Off Off
msgpack.php_only    On  On


Posted by 시니^^
Programming/PHP2014. 9. 16. 18:04

1. Redis List 데이터 사용 샘플소스


  1. <?php
  2. $redis = new Redis();
  3. try {
  4. $redis->connect('127.0.0.1', 6379, 2.5);//2.5 sec timeout
  5. //Auth Password(redis.conf requirepass)
  6. //$redis->auth('foobared');
  7. } catch (Exception $e) {
  8. exit( "Cannot connect to redis server : ".$e->getMessage() );
  9. }
  10. // //DB Select
  11. if ( !$redis->select(0) ){
  12. exit( "NOT DB Select");
  13. }
  14. $redis->delete('weblog:ws1');
  15. //rPush 맨아래 배열로 입력
  16. $redis->rPush('weblog:ws1', 'log1');
  17. $redis->rPush('weblog:ws1', 'log2');
  18. $redis->rPush('weblog:ws1', 'log3');
  19. $redis->rPush('weblog:ws1', 'log4');
  20. //lPush 첫번째 배열로 입력
  21. $redis->lPush('weblog:ws1', 'log5');
  22. //0~2번까지배열 가져오기
  23. var_dump($redis->lRange('weblog:ws1', 0, 2));
  24. //전체배열데이터 가져오기
  25. var_dump($redis->lRange('weblog:ws1', 0, -1));
  26. ?>

2. Redis 들어있는 데이터



3. 추가명령어 메뉴얼참조

https://github.com/nicolasff/phpredis#lists

blPop, brPop - Remove and get the first/last element in a list

brpoplpush - Pop a value from a list, push it to another list and return it

lIndex, lGet - Get an element from a list by its index

lInsert - Insert an element before or after another element in a list

lLen, lSize - Get the length/size of a list

lPop - Remove and get the first element in a list

lPush - Prepend one or multiple values to a list

lPushx - Prepend a value to a list, only if the list exists

lRange, lGetRange - Get a range of elements from a list

lRem, lRemove - Remove elements from a list

lSet - Set the value of an element in a list by its index

lTrim, listTrim - Trim a list to the specified range

rPop - Remove and get the last element in a list

rpoplpush - Remove the last element in a list, append it to another list and return it (redis >= 1.1)

rPush - Append one or multiple values to a list

rPushx - Append a value to a list, only if the list exists

Posted by 시니^^
Programming/PHP2014. 9. 16. 16:26


1. Redis Hash 데이터 사용 샘플 소스


  1. <?php
  2. $redis = new Redis();
  3. try {
  4. $redis->connect('127.0.0.1', 6379, 2.5);//2.5 sec timeout
  5. //Auth Password(redis.conf requirepass)
  6. //$redis->auth('foobared');
  7. } catch (Exception $e) {
  8. exit( "Cannot connect to redis server : ".$e->getMessage() );
  9. }
  10. // //DB Select
  11. if ( !$redis->select(0) ){
  12. exit( "NOT DB Select");
  13. }
  14. $redis->delete('user_list');
  15. $redis->hSet('user_list', 'uid1', 1);
  16. $redis->hSet('user_list', 'uid2', 2);
  17. $redis->hSet('user_list', 'uid3', 3);
  18. if ( $redis->hExists('user_list','uid1') ){
  19. echo "uid1 : ".$redis->hGet('user_list','uid1')."\n";
  20. }else{
  21. echo 'NOT_DATA';
  22. }
  23. //여러개 HASH 데이터 한번에 입력
  24. $redis->hMset('user_list', array('uid4' => 4, 'uid5' =>5));
  25. //여러개 HASH 데이터를 한번에 가져옴
  26. var_dump($redis->hMGet('user_list', array('uid4', 'uid5')));
  27. var_dump($redis->hGetAll('user_list'));
  28. /*
  29. * Print
  30. uid1 : 1
  31. array(2) {
  32. ["uid4"]=>
  33. string(1) "4"
  34. ["uid5"]=>
  35. string(1) "5"
  36. }
  37. array(5) {
  38. ["uid1"]=>
  39. string(1) "1"
  40. ["uid2"]=>
  41. string(1) "2"
  42. ["uid3"]=>
  43. string(1) "3"
  44. ["uid4"]=>
  45. string(1) "4"
  46. ["uid5"]=>
  47. string(1) "5"
  48. }
  49. */
  50. ?>


2. Redis 들어있는 데이터




3. 추가 명령어 메뉴얼 참조

https://github.com/nicolasff/phpredis#hashes

hDel - Delete one or more hash fields

hExists - Determine if a hash field exists

hGet - Get the value of a hash field

hGetAll - Get all the fields and values in a hash

hIncrBy - Increment the integer value of a hash field by the given number

hIncrByFloat - Increment the float value of a hash field by the given amount

hKeys - Get all the fields in a hash

hLen - Get the number of fields in a hash

hMGet - Get the values of all the given hash fields

hMSet - Set multiple hash fields to multiple values

hSet - Set the string value of a hash field

hSetNx - Set the value of a hash field, only if the field does not exist

hVals - Get all the values in a hash

hScan - Scan a hash key for members

Posted by 시니^^
Programming/PHP2014. 9. 16. 16:07

Connect와 기본 keys-and-strings 샘플자료


  1. <?php
  2. $redis = new Redis();
  3. try {
  4. $redis->connect('127.0.0.1', 6379, 2.5);//2.5 sec timeout
  5. //Auth Password(redis.conf requirepass)
  6. //$redis->auth('foobared');
  7. } catch (Exception $e) {
  8. exit( "Cannot connect to redis server : ".$e->getMessage() );
  9. }
  10. // //DB Select
  11. if ( !$redis->select(0) ){
  12. exit( "NOT DB Select");
  13. }
  14. $redis->set('key1','value1',10); //유효기간 10초
  15. echo $redis->get('key1');
  16. /*
  17. * print : value1
  18. */
  19. ?>


자세한 명령어 사용법은 아래 메뉴얼참조

https://github.com/nicolasff/phpredis#keys-and-strings


Strings

append - Append a value to a key

bitcount - Count set bits in a string

bitop - Perform bitwise operations between strings

decr, decrBy - Decrement the value of a key

get - Get the value of a key

getBit - Returns the bit value at offset in the string value stored at key

getRange - Get a substring of the string stored at a key

getSet - Set the string value of a key and return its old value

incr, incrBy - Increment the value of a key

incrByFloat - Increment the float value of a key by the given amount

mGet, getMultiple - Get the values of all the given keys

mSet, mSetNX - Set multiple keys to multiple values

set - Set the string value of a key

setBit - Sets or clears the bit at offset in the string value stored at key

setex, psetex - Set the value and expiration of a key

setnx - Set the value of a key, only if the key does not exist

setRange - Overwrite part of a string at key starting at the specified offset

strlen - Get the length of the value stored in a key


Keys

del, delete - Delete a key

dump - Return a serialized version of the value stored at the specified key.

exists - Determine if a key exists

expire, setTimeout, pexpire - Set a key's time to live in seconds

expireAt, pexpireAt - Set the expiration for a key as a UNIX timestamp

keys, getKeys - Find all keys matching the given pattern

scan - Scan for keys in the keyspace (Redis >= 2.8.0)

migrate - Atomically transfer a key from a Redis instance to another one

move - Move a key to another database

object - Inspect the internals of Redis objects

persist - Remove the expiration from a key

randomKey - Return a random key from the keyspace

rename, renameKey - Rename a key

renameNx - Rename a key, only if the new key does not exist

type - Determine the type stored at key

sort - Sort the elements in a list, set or sorted set

ttl, pttl - Get the time to live for a key

restore - Create a key using the provided serialized value, previously obtained with dump.

Posted by 시니^^
Programming/PHP2014. 9. 16. 12:32


http://redis.io/clients 

=> 공식 사이트 들어가보면  아래 두가지를 추천하는 듯함

Predis ☺ ★ Repository JoL1hAHN Mature and supported

phpredis ☺ ★ Repository yowgi This is a client written in C as a PHP module.


아무래도 C로 작성된 PHP 모듈이 성능이 더 좋지 않을가?? 라는 생각에 아래 phpredis 하기로함
테스트는 해봐야겠지만.............
그리고 보니까...  https://github.com/nicolasff/phpredis#php-session-handler 도 지원함 좋다!!

설치방법 아래 참조

$ wget https://github.com/nicolasff/phpredis/zipball/master -O phpredis.zip
$ unzip phpredis.zip 
$ ll
drwxr-xr-x  5 root root   4096 Sep  3 04:27 nicolasff-phpredis-4c1f1bc

$ cd nicolasff-phpredis-4c1f1bc/
$ phpize 
Can't find PHP headers in /usr/include/php
The php-devel package is required for use of this command.

$ yum install php-devel #PHP devel 미설치시 설치하기!
$ phpize
Configuring for:
PHP Api Version:         20121113
Zend Module Api No:      20121212
Zend Extension Api No:   220121212

$ ./configure
$ make && make install
Installing shared extensions:     /usr/lib64/php/modules/

$ cd /usr/lib64/php/modules/
$ ll | grep redis
-rwxr-xr-x 1 root root  942112 Sep 16 12:11 redis.so

##### php.conf 디렉토리에 맞게 ini 에 extension 등록하기! 안되면 php.ini등록해도됨
$ echo extension=redis.so > /etc/php.d/redis.ini 


##### 웹서버종류에 따라서 Apache Restart 또는 php-fpm restart
$ /etc/init.d/php-fpm restart

##### 최종확인
$ php -i | grep 'Redis Version'
Redis Version => 2.2.5

<?php phpinfo() ?> 
redis
Redis Support => enabled
Redis Version => 2.2.5


Posted by 시니^^
Programming/PHP2014. 9. 4. 15:43


Anonymous functions - http://php.net/manual/ro/functions.anonymous.php


있다는 것만 알지.. 사용하지 않았다.. 

그런데 구글링 중 괜찮은 활용 방법을 찾아서!! 왠지 jquery 하는듯한 느낌은 뭐지...;;

 - 특정 배열값 파싱하거나 재구성할때 for문 안돌리고 array_map 이용할때 괜찮은듯함.

예) http://stackoverflow.com/questions/13435747/how-can-i-remove-the-file-extension-from-each-string-in-a-php-array


  1. <?php
  2. # your array
  3. $slike = array('1.jpg','253455.jpg','32.jpg','477.jpg');
  4. # if you have PHP >= 5.3, I'd use this
  5. $slike = array_map(function($e){
  6. return pathinfo($e, PATHINFO_FILENAME);
  7. }, $slike);
  8. # if you have PHP <= 5.2, use this
  9. $slike = array_map('pathinfo', $slike, array_fill(
  10. 0, count($slike), PATHINFO_FILENAME
  11. ));
  12. # dump
  13. print_r($slike);
  14. /*print
  15. Array
  16. (
  17. [0] => 1
  18. [1] => 253455
  19. [2] => 32
  20. [3] => 477
  21. )
  22. */
  23. ?>


※ 단 PHP 5.3 이상부터 가능함!

Posted by 시니^^
SERVER/Nginx2014. 8. 29. 15:28
IE나 크롬 개발자 도구로 Response Headers 보게 되면  아래와 같이 서버버젼과 PHP버젼이 적나하게 보이는 경우가 있다
항상 버젼 업데이트를 한다고 하면 문제 없겠지만 늘 버그/보안취약점이 나와서 버젼 업데이트가 되고 있는 중에 
해당 버젼을 확인하고 취약점을 해킹하는 경우가 발생한다 그래서 해당 정보의 경우 숨기는 게 보다 안전하다고 생각된다.

  1. Cache-Control:
    no-store, no-cache, must-revalidate, post-check=0, pre-check=0
  2. Connection:
    keep-alive
  3. Content-Type:
    text/html; charset=UTF-8
  4. Date:
    Fri, 29 Aug 2014 06:22:59 GMT
  5. Expires:
    Thu, 19 Nov 1981 08:52:00 GMT
  6. Pragma:
    no-cache
  7. Server:
    nginx/1.6.1
  8. Transfer-Encoding:
    chunked
  9. X-Powered-By:
    PHP/5.5.15


※ X-Powered-By:PHP/5.5.15 삭제

vi /etc/php.ini

expose_php = Off <== OFF로 변경


※ Nginx 숨기기

http://wiki.nginx.org/HttpCoreModule#server_tokens

vi /etc/nginx/nginx.conf

server_tokens off; <==내용추가함


=> php와 nginx수정하였다면 php-fpm과 nginx 재시작해줘야됨


※ Nginx라는 서버이름을 바꾸고 싶을때

1. HttpHeadersMoreModule 추가모듈설치 하여서 셋팅

http://wiki.nginx.org/HttpHeadersMoreModule#Installation

※ 소스설치시 추가하면됨

./configure --prefix=/opt/nginx --add-module=/path/to/headers-more-nginx-module

※ set the Server output header 

    more_set_headers 'Server: my-server';


2. 컴파일전에 소스코드에서 해당내용 삭제 또는 변경 

http://forum.nginx.org/read.php?11,1646

vi /path/to/nginx-0.*/src/http/ngx_http_header_filter_module.c lines 48 and 49:

====================================================

static char ngx_http_server_string[] = "Server: nginx" CRLF;

static char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;

====================================================


※ Apache 경우

vi /etc/httpd/conf/httpd.conf

ServerTokens Prod

ServerSignature Off

=====================================================

ServerTokens Prod[uctOnly] => Server: Apache
ServerTokens Major => Server: Apache/2
ServerTokens Minor => Server: Apache/2.0
ServerTokens Min[imal] => Server: Apache/2.0.41
ServerTokens OS : Server => Apache/2.0.41 (Unix)
ServerTokens Full : Server => Apache/2.0.41 (Unix) PHP/4.2.2 MyMod/1.2


Posted by 시니^^
Programming/PHP2014. 5. 22. 16:49
SQL Server Native를 설치해서 사용했지만 아래 링크처럼 한글 및 기타 몇가지 문제가 있는듯하여서
FreeTDS로 사용하기로 했다..

Linux uninxODBC SQL Server Native Client 11.0 한글문제 - http://www.opens.kr/35


※ SQL Server Native bind 처리도 문제있는 듯하다 ㅠㅠ

http://hbs.pe.kr/50113950707

http://connect.microsoft.com/SQLServer/feedback/details/521409/odbc-client-mssql-does-not-work-with-bound-parameters-in-subquery

※ FreeTDS bindValue 쓰면 되는 것 처럼 보이는 데 

    실제 SQL Server Profiler 해보면 prepare statement bind 안되어서 들어온다ㅠㅠ;;


PHP5.3/5.4/5.5 Yum 설치 - http://www.opens.kr/33  으로 PHP 설치 사용했다면

그냥 yum install php55w-mssql 만 설치하면 자동으로 설치가 다 된다.


1) 설치

$ yum install php55w-mssql ================================================================================== Package Arch Version Repository Size ================================================================================== Installing: php55w-mssql x86_64 5.5.12-1.w6 Installing for dependencies: freetds x86_64 0.91-2.el6 php55w-pdo x86_64 5.5.12-1.w6 unixODBC x86_64 2.2.14-12.el6_3 Transaction Summary ================================================================================== Install 4 Package(s)


2) 접속 테스트 아래 링크에 tsql / isql 이용해서 하면된다.

리눅스 unixODBC FreeTDS 설치 (MSSQL) - http://www.opens.kr/36


3) 글로벌 설정

$ vi /etc/freetds.conf
------------------------
[global]
tds version = 8.0
client charset = UTF-8
text size = 64512
timeout = 10
connect timeout = 10
------------------------

※ TDS protocol 버전정보와 자세한 옵션 정보는 아래 freetds 사이트 가이드 참조하면 된다.

http://www.freetds.org/userguide/choosingtdsprotocol.htm

http://www.freetds.org/userguide/


4) PHP PDO에서 접속예시 

$dsn = 'dblib:host=192.168.0.0;dbname=DBNAME';
$user = "user_id";
$password = "user_password";

try {
    $dbh = new PDO($dsn, $user, $password); 
} catch (PDOException $e) {
    echo $e->getMessage();
}
$sQuery = "select * from sysobjects where xtype = 'U'";
$sth =  $dbh->prepare($sQuery);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($result);



Posted by 시니^^