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

  1. 2013.05.14 날짜, 시간관련 함수
  2. 2013.05.14 문자열 절반 마킹
  3. 2013.05.14 숫자만 리턴 함수
  4. 2013.05.14 백분율, 퍼센트 함수
  5. 2013.05.14 공백제거 함수
  6. 2013.05.02 숫자를 한글 원 단위로 변경하는 함수
  7. 2012.01.09 mcrypt 암호화 모듈
  8. 2011.09.29 페이지 소스 가져오는 함수
  9. 2011.02.01 Pear MDB2 연결파일
  10. 2010.12.01 소켓을 통한 메일 발송함수
2013. 5. 14. 14:41

날짜, 시간관련 함수


/**
 * datetime 형식을 date 형식만 가져옴
 * @param string $datetime
 * @return string
 */
function datetime2date($datetime) {
    if(empty($datetime))
        return $datetime;
    
	$tmp = explode(' ',$datetime);
	return $tmp[0];
}
/**
 * datetime 형식을 time 형식만 가져옴
 * @param string $datetime
 * @return string
 */
function datetime2time($datetime) {
    if(empty($datetime))
        return $datetime;
        
    $tmp = explode(' ',$datetime);
	return $tmp[1];
}
/**
 * datetime을 2줄로 출력
 * @param datetime $datetime
 * @return DateTime
 */
function datetime2br($datetime) {
    return str_replace(' ','<br />',$datetime);
}
/**
 * datetime을 배열로 변환
 * @param datetime $datetime
 */
function datetime2array($datetime) {
    return sscanf($datetime, '%4d-%2d-%2d %2d:%2d:%2d');
}
/**
 * datetime을 date 요일 현태로 리턴
 * @param datetime $datetime
 * @return string
 */
function datetime2format($datetime) {
    $tmp = strtotime($datetime);
    $w = date('w', $tmp);
    return date('Y.m.d '.get_week_hangul($w), $tmp);
}
/**
 * D-DAY 계산
 * @param date $ddate
 * @param date $ndate
 * @return int
 */
function dday($ddate, $ndate) {
    $tmp = strtotime($ddate) - strtotime($ndate);
    $dday = ceil($tmp / 86400);
    if($dday < 0)
        return 'D - '.abs($dday);
    else if($dday > 0)
        return 'D + '.$dday;
    else
        return '';
}
/**
 * 숫자를 요일로 변환
 * @param int $wcode
 */
function get_week_hangul($wcode) {
    $rtn = array('일','월','화','수','목','금','토');
    return $rtn[$wcode];
}
/**
 * 현재 분기 리턴
 */
function now_quater() {
    $m = date('n');
    if($m < 4)
        return 1;
    else if($m > 3 && $m < 7)
        return 2;
    else if($m > 6 && $m < 10)
        return 3;
    else 
        return 4;
}
/**
 * 분기를 시작일,종료일(날짜시간)으로 리턴
 * @param int $year 년
 * @param int $quater 분기
 */
function quater2datetime($year, $quater) {
    if($quater == 1)
        return array($year.'-01-01 00:00:00',$year.'-03-31 23:59:59');
    else if($quater == 2)
        return array($year.'-04-01 00:00:00',$year.'-06-30 23:59:59');
    else if($quater == 3)
        return array($year.'-07-01 00:00:00',$year.'-09-30 23:59:59');
    else
        return array($year.'-10-01 00:00:00',$year.'-12-31 23:59:59');
}
/**
 * 초를 시분초로 변경
 * @param int $sec 초
 * @return string
 */
function sec2hms($sec) {
	$rtn = '';
	$hour = (int)($sec / 3600);
	if($hour) {
		$sec = $sec - $hour * 3600;
		$rtn .= $hour.'시간 ';
	}
	$min = (int)($sec / 60);
	if($min) {
		$sec = $sec - $min * 60;
		$rtn .= $min.'분 ';
	}
	if($sec)
		return $rtn.$sec.'초';
	else
		return $rtn;
}

2013. 5. 14. 14:37

문자열 절반 마킹


/**
 * 문자열 절반 마킹
 * @param string $str
 * @param int $char
 * @param string $charset
 * @return string
 */
function marking($str, $char = '*', $charset = 'UTF-8') {
    $len = mb_strlen($str, $charset);
    $pos = ceil($len / 2);
    if($len > 14)
        return str_repeat($char, $len - $pos).mb_substr($str, $pos, $len - $pos, $charset);
    else
        return mb_substr($str, 0, $pos, $charset).str_repeat($char, $len - $pos);
}

2013. 5. 14. 14:36

숫자만 리턴 함수


/**
 * 숫자만 리턴
 * @param string $hp
 */
function only_num($hp) {
    return preg_replace('/[^0-9]/','',$hp);
}

2013. 5. 14. 14:35

백분율, 퍼센트 함수


/**
 * 백분율 연산
 * @param int $numerator 분자
 * @param int $denominator 분모
 * @param int $len 소숫점 이하 길이
 */
function percentage($numerator, $denominator, $len = 0, $zero = '-') {
    if(!$numerator && !$denominator)
        return $zero;
    else if(!$denominator)
        return number_format($numerator * 100, $len);
        
    return number_format($numerator/$denominator*100, $len);
}

2013. 5. 14. 14:34

공백제거 함수


/**
 * 공백삭제
 * @param string $str
 * @return mixed
 */
function del_space($str) {
    return preg_replace('/\s+/', '', $str);
}

2013. 5. 2. 20:55

숫자를 한글 원 단위로 변경하는 함수

숫자를 한글 원단위로 바꿔주는 함수가 필요해서 만들어 보았다.

만들다보니 두가지 방법으로 구현을 하게 되었는데 둘다 4자리 기준으로 구분하는건 동일하다.


전자는 php 기본함수인 str_split로 4자리씩 나누는 방식으로 먼저 4자리로 끈어지도록 맨 앞에 모자라는 자릿수만 큼 0 을 붙인후에 str_split로 나누는 방식이고


후자는 길이에 따라 뒤에서 4자리씩 substr로 잘라나오는 방식이다.


두개를 만들어 놓으니 어느게 더 효울적일까 해서 100회씩 반복한후 평균 실행 시간 측정을 해보았는데


전자는 0.0022....... 초가 걸리고 후자는 0.0024....... 초가 걸려서 전자가 더 효율 적인 방식이라고 할 수 있겠다.


function number2won($num) { 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); for($i=0,$cnt=count($arr);$i<$cnt;$i++) { if($tmp = (int)$arr[$i]) $rtn .= $tmp.$won[$cnt - $i - 1]; } return $rtn; } function number2won2($num) { if(!ctype_digit($num)) $num = (string)$num; $won = array('', '만', '억', '조', '경', '해'); $rtn = ''; $len = strlen($num); for($i=0,$cnt=ceil($len/4);$i<$cnt;$i++) { $spos = $len - ($i + 1) * 4; $epos = 4; if($spos < 0) { $epos += $spos; $spos = 0; } if($tmp = (int)substr($num, $spos, $epos)) $rtn = $tmp.$won[$i].$rtn; } return $rtn; }


2012. 1. 9. 19:17

mcrypt 암호화 모듈

/** * encrypt, decrypt 관련 함수 * * @author Yongseok Kang <wyseburn(at)gmail.com> * @since 2011. 7. 13. * @category * @version 1.0 */ define('ENC_KEY', 'enckey!@#$'); //키 값 /** * 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) { return bin2hex(gzcompress(mcrypt_ecb(MCRYPT_RIJNDAEL_192, md5(ENC_KEY), $str, MCRYPT_ENCRYPT))); } /** * 키를 통해 복호화 * @param string $str */ function m_decrypt($str) { return trim(mcrypt_ecb(MCRYPT_RIJNDAEL_192, md5(ENC_KEY), gzuncompress(hex2bin($str)), MCRYPT_DECRYPT)); }


2011. 9. 29. 15:58

페이지 소스 가져오는 함수


<?php
/**
 * 웹페이지 소스 가져오는 함수
 *
 * @param text $url
 * @param array(
 *                  'method' => 'GET/POST',
 *                  'port' => 80,
 *                  'cookie'=> array (
 *                                      'key' => 'value',
 *                                      'key' => 'value'
 *                                  ),
 *                  'referer' => 'http://domain.com',
 *               ) $opt
 * @return array
 */
function getPageSource($url, $opt = array()) {
    
    $result = array('','');
    
    if(empty($opt)) {
        $opt['method'] = 'GET';
        $opt['port'] = 80;
    }
    else {
        if(isset($opt['method'])) {
            $opt['method'] = strtoupper($opt['method']);
            if($opt['method'] !== 'GET' && $opt['method'] !== 'POST') {
                exit("FUNCTION getPageSource ERROR : \$opt['method'] is only GET or POST");
            }
        }
        
        if(empty($opt['port'])) {
            $opt['port'] = 80;
        }
    }
    
    $url_info = parse_url($url);
    $fp = fsockopen($url_info['host'], $opt['port']);

    if(!$fp) {
        return array();
    }
    
    fputs($fp,$opt['method']." ".$url_info['path'].($opt['method'] === 'GET' && $url_info['query'] ? '?'.$url_info['query'] : '')." HTTP/1.0\r\n");
    fputs($fp,"Host: ".$url_info['host']."\r\n");
    fputs($fp,"User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)\r\n");
    
    if(isset($opt['referer'])) {
        fputs($fp,"Referer: ".$opt['referer']."\r\n");
    }
    
    if(isset($opt['cookie'])) {
        foreach($opt['cookie'] as $value => $key) {
            fputs($fp,"Cookie: ".$key."=".urlencode($value).";\r\n");
        }
    }
    
    if($opt['method'] === 'POST') {
        fputs($fp,"Content-Type: application/x-www-form-urlencoded\r\n");
        fputs($fp,"Content-Length: ".strlen($url_info['query'])."\r\n");
        fputs($fp,"Connection: close\r\n\r\n");
        fputs($fp,$url_info['query']);
    }
    else {
        fputs($fp,"Connection: close\r\n\r\n");
    }
    
    while(trim($buf = fgets($fp,1024))) {  //respose header 부분을 읽어옵니다.
        $result[0] .= $buf;
    }

    while(!feof($fp)) {  //response body 를 읽어옵니다.
        $result[1] .= fgets($fp,1024);
    }
    
    fclose($fp);
    
    return $result;
}
?>

2011. 2. 1. 11:00

Pear MDB2 연결파일

<?php
require_once 'MDB2.php';

function dbDisconnect() {
    global $res,$db;

    if(isset($res)) {
        $res->free();
    }

    $db->disconnect();
}

function procPearError($arg) {
    $header  = 'MIME-Version: 1.0' . "\r\n";
    $header .= 'Content-type: text/html; charset=EUC-KR' . "\r\n";
    $header .= "From: 페이지오류 <임의메일주소>\r\n"; //optional headerfields
    $message = "<pre>http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."\r\n\r\n".$arg->getUserInfo()."</pre>";
    @mail("메일주소", "Page error found", $message, $header);
    exit('DB 오류<BR /><BR /><pre>'.$arg->getUserInfo().'</pre><BR /><BR />계속 오류가 발생할경우 관리자에게 문의해주세요.<br /><br /><a href="javascript:history.back()">[뒤로가기]</a>');
}

// 페이지 종료시 처리할 콜백함수
register_shutdown_function('dbDisconnect');

// PEAR 오류시 처리할 콜백함수
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK,'procPearError');

$dsn = '디비종류://아이디:비번@서버/데이타베이스명';

$options = array(
    'debug'       => 2, //실제 운영시 0
    'portability'    => MDB2_PORTABILITY_FIX_CASE
);

$db =& MDB2::factory($dsn, $options);
$db->setFetchMode(MDB2_FETCHMODE_ASSOC);
?>

2010. 12. 1. 09:36

소켓을 통한 메일 발송함수

PHP의 mail() 함수가 동작하지 않거나 localhost 에 smtp가 설치되지 않아서 다른 서버의 smtp를 이용하여 메일을 전송할 때 사용

function sendmail($subject, $body, $from, $to, $type = 'text/html') {
	$smtp_id = "아이디"; 
	$smtp_pwd = "비번";
	$host = "아이피";
	
	$fp = fsockopen($host, 25, &$errno, &$errstr, 10);
	if(!$fp) {
		exit('메일오류 ['.$errno.'] '.$errstr);
	}
	fgets($fp, 128);  
	fputs($fp, "helo $host\r\n");  
	fgets($fp, 128);
	
	// 로긴
	fputs($fp, "auth login\r\n"); 
	fgets($fp,128); 
	fputs($fp, base64_encode($smtp_id)."\r\n"); 
	fgets($fp,128); 
	fputs($fp, base64_encode($smtp_pwd)."\r\n"); 
	fgets($fp,128); 
	
	fputs($fp, "mail from: <$from>\r\n");  
	$returnvalue[0] = fgets($fp, 128);  
	fputs($fp, "rcpt to: <$to>\r\n");  
	$returnvalue[1] = fgets($fp, 128); 
	fputs($fp, "data\r\n");  
	fgets($fp, 128);  
	fputs($fp, "Return-Path: $from\r\n");  
	fputs($fp, "From: \"$from\" <$from>\r\n");  
fputs($fp, "To: <$to>\r\n"); fputs($fp, "Subject: $subject\r\n"); fputs($fp, "Content-Type: ".$type."; charset=\"euc-kr\"\r\n"); fputs($fp, "\r\n"); //$body = chunk_split(base64_encode($body)); fputs($fp, $body); fputs($fp, "\r\n"); fputs($fp, "\r\n.\r\n"); $returnvalue[2] = fgets($fp, 128); fclose($fp); //print_r($returnvalue); if (preg_match("/^250/", $returnvalue[0])&&preg_match("/^250/", $returnvalue[1])&&preg_match("/^250/", $returnvalue[2])) { return true; } else { return false; } } if(sendmail('제목', '내용', '발신', '수신')) echo '성공'; else echo '실패';