'자작소스/PHP'에 해당되는 글 50건

  1. 2017.05.11 [PHP] MySQL 모든 테이블에서 특정 필드 존재하는지 확인 후 특정 작업하기
  2. 2016.12.30 서브도메인 가져오는 정규식 코드
  3. 2016.10.05 간단한 쿠폰코드 생성로직
  4. 2016.05.10 AES128 CBC PKCS5 HMAC(SHA256) 암/복호화(PHP)
  5. 2016.02.18 conf 파일 리더
  6. 2014.01.16 숫자를 한글원단위로 바꾸는 함수
  7. 2013.09.05 uri 생성(get, post, request, global)
  8. 2013.08.06 mcrypt pkcs5 패딩 적용 라이브러리
  9. 2013.05.14 캡차 관련
  10. 2013.05.14 폼처리 관련 함수
2017. 5. 11. 16:28

[PHP] MySQL 모든 테이블에서 특정 필드 존재하는지 확인 후 특정 작업하기

m_idx 라는 필드를 가지는 테이블에서 특정 레코드값을 다른 db로 그대로 옮기는 작업, 여러가지로 응용 가능할 것임


2016. 12. 30. 15:21

서브도메인 가져오는 정규식 코드

서브도메인 가져오는 PHP코드
 


주의 : 정규식 보면 알겠지만 .com 과 같이  3글자, co.kr 과 같이 2.2 글자 도메인만 대응됨.

사용하는 도메인에 맞게 고쳐서 사용.

2016. 10. 5. 17:58

간단한 쿠폰코드 생성로직

db테이블로 간단하게 쿠폰코드를 생성하는 로직.
md5를 다른 해시 함수로 바꿔서 변경해서 길이를 다르게 할수도.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php 
 
function getCouponCode() {
    while(true) {
        $hash = md5(microtime());
        $codes = sscanf($hash'%8s%8s%8s%8s');
        $db_codes = $this->db->query("SELECT coupon FROM coupon_table WHERE coupon IN ('".implode("','"$codes)."')")->fetchAll(PDO::FETCH_COLUMN);
        if(count($db_codes< count($codes)) {
            $coupon_codes = array_diff($codes$db_codes);
            $this->db->exec("INSERT INTO coupon_table (coupon) VALUES ('{$coupon_codes[0]}')");
            return $coupon_codes[0];
        }
    }
}
cs



2016. 5. 10. 15:11

AES128 CBC PKCS5 HMAC(SHA256) 암/복호화(PHP)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
namespace Lib;
 
define('ENC_KEY', hex2bin(md5('비밀키')));
define('ENC_IV', hex2bin(md5('IV키')));
define('ENC_HASH', hex2bin(md5('HMAC키')));
 
class Mcrypt {
    /**
     * PKCS5 패드추가
     * @param string $text
     * @param int $blocksize
     * @return string
     */
    public static function pkcs5_pad ($text$blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    /**
     * PKCS5 패드제거
     * @param string $text
     * @return boolean|string
     */
    public static function pkcs5_unpad($text) {
        $pad = ord($text{strlen($text)-1});
        if ($pad > strlen($text)) return false;
        if (strspn($text, chr($pad), strlen($text- $pad!= $padreturn false;
        return substr($text0-1 * $pad);
    }
 
    /**
     * 암호화
     * @param string $str
     * @return string
     */
    public static function encrypt($str)
    {
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
        $input = self::pkcs5_pad($str$size);
        $cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, ENC_KEY, $input, MCRYPT_MODE_CBC, ENC_IV);
        $hmac = hash_hmac('sha256'$cipher, ENC_HASH, true);
 
        return base64_encode($cipher.$hmac);
    }
 
    /**
     * 복호화
     * @param string $str
     * @return bool|string
     */
    public static function decrypt($str)
    {
        $cipher = @base64_decode($str);
        if($cipher === false)
            return false;
        $len = strlen($cipher);
        if($len < 48)
            return false;
        $hmac = substr($cipher-32);
        $ciphertext = substr($cipher0$len - 32);
 
        $hmac_check = hash_hmac('sha256'$ciphertext, ENC_HASH, true);
        if($hmac !== $hmac_check)
            return false;
 
        $plaintext = @mcrypt_decrypt(MCRYPT_RIJNDAEL_128, ENC_KEY, $ciphertext, MCRYPT_MODE_CBC, ENC_IV);
        if($plaintext === false)
            return false;
        else
            return self::pkcs5_unpad($plaintext);
    }
}



2016. 2. 18. 17:22

conf 파일 리더

ActionScript 쪽에서 PropertiesConfigurationFactory 라는 클래스를 통해 아래와 같은 형식의 파일 내용을 읽어 들이는데 PHP에서도 읽을 필요가 있어서 간단히 제작함


KEY = 내용내용

KEY2 = 내용내용

#KEY3 = 주석

//KEY4 = 주석


<?php class ConfReader { /** * @var array */ private $_data; /** * @param $key * @return null|string */ public function get($key) { if(isset($this->_data[$key])) return $this->_data[$key]; else return null; } /** * @return array */ public function getAll() { return $this->_data; } /** * @param $filename string * @return bool */ public function load($filename) { if(!file_exists($filename)) return false; $fp = fopen($filename, 'r'); while(!feof($fp)) { $buf = trim(fgets($fp, 1024)); if(empty($buf) || $buf[0] == '#' || ($buf[0] == '/' && $buf[1] == '/')) continue; $tmp = explode('=', $buf); $cnt = count($tmp); if($cnt < 2) continue; elseif($cnt == 2) { $key = trim($tmp[0]); $value = trim($tmp[1]); if(empty($key)) continue; $this->_data[$key] = $value; } else { $key = trim($tmp[0]); $value = ""; for($i=1;$i<$cnt;++$i) { if($i == 1) $value .= $tmp[$i]; else $value .= "=".$tmp[$i]; } if($value) $this->_data[$key] = trim($value); } } fclose($fp); return true; } }


2014. 1. 16. 19:04

숫자를 한글원단위로 바꾸는 함수


/**
 * 숫자를 원단위로 변환
 * @param string $num
 * @param int $cut_block
 * @return string
 */
function number2won($num, $cut_block = 0) {
    if(!$num)
        return '0';
    if($num < 0) {
        $sign = '-';
        $num = $num * -1;
    }
    else {
        $sign = '';
    }
    if(!ctype_digit($num))
        $num = (string)$num;
        
    $won = array('', '만', '억', '조', '경', '해');
    $rtn = '';
    $len = strlen($num);
    $mod = $len % 4;
    if($mod) {
        $mod = 4 - $mod;
        $num = str_pad($num, $len + $mod, '0', STR_PAD_LEFT);
    }
    
    $arr = str_split($num, 4);
    $cnt=$cnt2=count($arr);
    if($cut_block) {
        if($cnt > $cut_block)
            $cnt = $cut_block;
    }        
    for($i=0;$i<$cnt;$i++) {
        if($tmp = (int)$arr[$i]) {
            if($i)
                $rtn .= ' '.$tmp.$won[$cnt2 - $i - 1];
            else
                $rtn .= $tmp.$won[$cnt2 - $i - 1];
        }
    }
    return $sign.$rtn;
}

2013. 9. 5. 17:30

uri 생성(get, post, request, global)


/**
 * uri 생성
 * @param string $mode
 * @param array $param
 */
function create_uri($mode, $param) {
    $rtn = '';
    if($mode == 'global') {
        for($i=0,$cnt=count($param);$i<$cnt;$i++) {
            $rtn .= '&'.$param[$i].'='.(isset($GLOBALS[$param[$i]])?$GLOBALS[$param[$i]]:'');
        }
    }
    else if($mode == 'post') {
        for($i=0,$cnt=count($param);$i<$cnt;$i++) {
            $rtn .= '&'.$param[$i].'='.(isset($_POST[$param[$i]])?$_POST[$param[$i]]:'');
        }
    }
    else if($mode == 'request') {
        for($i=0,$cnt=count($param);$i<$cnt;$i++) {
            $rtn .= '&'.$param[$i].'='.(isset($_REQUEST[$param[$i]])?$_REQUEST[$param[$i]]:'');
        }
    }
    else {
        for($i=0,$cnt=count($param);$i<$cnt;$i++) {
            $rtn .= '&'.$param[$i].'='.(isset($_GET[$param[$i]])?$_GET[$param[$i]]:'');
        }
    }
    return $rtn;
}

2013. 8. 6. 10:09

mcrypt pkcs5 패딩 적용 라이브러리

일반적으로 C, C++, .net등에서는 PKCS5패딩을 기본으로 사용하지만 PHP는 Zeros패딩만 사용하기때문에

암/복호화가 안된다. PHP쪽에서 PKCS5패딩을 사용하도록 적용한 라이브러리

/**
 * mcrypt 관련 함수
 */

define('ENC_KEY', hex2bin(md5('키값')));
define('ENC_IV', hex2bin(md5('IV값')));

/**
 * PKCS5 패딩추가
 * @param string $text
 * @param int $blocksize
 * @return string
 */
function pkcs5_pad ($text, $blocksize) { 
    $pad = $blocksize - (strlen($text) % $blocksize); 
    return $text . str_repeat(chr($pad), $pad); 
} 
/**
 * PKCS5 패딩제거
 * @param string $text
 * @return boolean|string
 */
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); 
}
/**
 * hex2bin
 * @param string $hexdata
 */
function hex2bin($hexdata) {
    $bindata="";
    for ($i=0,$cnt=strlen($hexdata);$i<$cnt;$i+=2) {
        $bindata .= chr(hexdec(substr($hexdata,$i,2)));
    }
    return $bindata;
}
/**
 * 키를 통해 암호화
 * @param string $str
 */
function m_encrypt($str) {
    $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc'); 
    $input = pkcs5_pad($str, $size); 
    
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, ENC_KEY, $input, MCRYPT_MODE_CBC, ENC_IV));
}
/**
 * 키를 통해 복호화
 * @param string $str
 */
function m_decrypt($str) {
    return pkcs5_unpad(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, ENC_KEY, base64_decode($str), MCRYPT_MODE_CBC, ENC_IV));
}


2013. 5. 14. 14:45

캡차 관련


/**
 * 랜던한 문자열을 길이만큼 반환
 * @param int $length
 * @param string $chars
 * @return string
 */
function getRandStr($length = 32, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890') {
    $chars_length = (strlen($chars) - 1); 
    $string = $chars{rand(0, $chars_length)};
    for ($i = 1; $i < $length; $i = strlen($string)) {
        $r = $chars{rand(0, $chars_length)};         
        if ($r != $string{$i - 1}) $string .=  $r;
    }     
    return $string;
}

/**
 * 캡차처리(getRandStr 필요함, func.other.php)
 * @param string $text
 * @param int $font_size
 * @param int $width
 * @param int $height
 * @param int $xpos
 * @param int $ypos
 */
function captcha($font_size, $width, $height, $xpos, $ypos) {
    $text = getRandStr(6, $chars = 'abcdefghijkmnpqrstuvwxyz23456789');
    $_SESSION['sess_captcha'] = $text;
    
    header ("Content-type: image/png");
    
    $im = imagecreate($width, $height);
    $white = imagecolorallocate ($im, 240, 240, 240); 
    $grey = imagecolorallocate ($im, 110, 110, 110); 

    imagettftext($im, $font_size, 0, $xpos, $ypos, $grey, CFG_LIB_PATH.'/fonts/unispace.ttf', $text);
    
    imagepng($im); 
    imagedestroy($im); 
}

2013. 5. 14. 14:42

폼처리 관련 함수


/**
 * 주민번호 유효성 검사
 * @param $string $jumin
 */
function validate_jumin($jumin) {
	// 형태 검사: 총 13자리의 숫자, 7번째는 1..4의 값을 가짐
	if (!preg_match('/^[0-9]{6}[1-4][0-9]{6}$/', $jumin))
		return false;
	
	// 날짜 유효성 검사
	$birthYear = ('2' >= $jumin[6]) ? '19' : '20';
	$birthYear += substr($jumin, 0, 2);
	$birthMonth = substr($jumin, 2, 2);
	$birthDate = substr($jumin, 4, 2);
	if (!checkdate($birthMonth, $birthDate, $birthYear))
		return false;
	
	// Checksum 코드의 유효성 검사
	for ($i = 0; $i < 13; $i++) $buf[$i] = (int) $jumin[$i];
	$multipliers = array(2,3,4,5,6,7,8,9,2,3,4,5);
	for ($i = $sum = 0; $i < 12; $i++) $sum += ($buf[$i] *= $multipliers[$i]);
	if ((11 - ($sum % 11)) % 10 != $buf[12])
		return false;
	
	// 모든 검사를 통과하면 유효한 주민등록번호임
	return true;
}

/**
 * select태그 생성 헬퍼
 * @param string $name name/id
 * @param array $options option들
 * @param string $select 선택값
 * @return string
 */
function make_select($name, $options, $select = '', $desc = '선택', $tag = '') {
    $rtn = '<select name="'.$name.'" id="'.$name.'" '.$tag.'>';
    if($desc !== NULL)
        $rtn .= '<option value="" '.(!$select?'select="select"':'').'>'.$desc.'</option>';
    foreach($options as $key => $val) {
        $rtn .= '<option value="'.$key.'" '.((string)$key===(string)$select?'selected="selected"':'').'>'.$val.'</option>';
    }
    $rtn .= '</select>';
    return $rtn;
}
/**
 * 숫자셀렉트
 * @param string $name name/id
 * @param int $syear
 * @param int $eyear
 * @param mixed $select
 * @param string $desc
 * @param string $tag
 * @return string
 */
function make_select_num($name, $snum, $enum, $select = NULL, $desc = NULL, $tag = '') {
    $rtn = '<select name="'.$name.'" id="'.$name.'" '.$tag.'>';
    if($desc !== NULL) {
        $rtn .= '<option value="" '.(!$select?'select="select"':'').'>'.$desc.'</option>';
    }
    for($i=$snum;$i<=$enum;$i++) {
        $rtn .= '<option value="'.$i.'" '.($i==$select?'selected="selected"':'').'>'.$i.'</option>';
    }
    $rtn .= '</select>';
    return $rtn;
}
/**
 * select 태그(telecom) 생성 헬퍼
 * @param string $name name/id
 * @param string $select 선택값
 * @return string
 */
function make_telecom($name, $select = '') {
    $options = array(
        'SKT' => 'SKT',
        'KTF' => 'KT',
        'LGT' => 'LGT'
    );
    $rtn = '<select name="'.$name.'" id="'.$name.'">';
    $rtn .= '<option value="" '.(!$select?'select="select"':'').'>통신사</option>';
    foreach($options as $key => $val) {
        $rtn .= '<option value="'.$key.'" '.((string)$key===(string)$select?'selected="selected"':'').'>'.$val.'</option>';
    }
    $rtn .= '</select>';
    return $rtn;
}