우분투2012. 7. 26. 20:50

1. crontab 사용법 

 

 분

 시

 일

 월

 요일

 명령어

 설명

 0-59

 0-23

 0-31

 1-12

 0-7

 실행할 파일 또는 명렁어

 

 30

 4,12

 *

cd /var/www/test; ./auto_sms.php

 매월 매주 매일 4시,12시 30분에 해당파일을 실행 시킨다.

 40

 1

 *

 *

 0

 

cd /var/www/test; ./auto_sms.php

 매월 매주일요일 1시 40분에 해당파일을 실행 시킨다.

 

2.등록 및 수정

 

 # crontab -e

  vi 형식의 에디터 창이 나오면 i 키로 등록할 명령어를 입력한다.

* * * * * /usr/home/test.sh >> /dev/null   : 1 분간격으로 해당 파일을 실행 하고 오류 저장을 하지 않는다.

 

3. .목록 확인

 

# crontab -l

 

4. 목록 수정

 

# crontab -e

 

# crontab -u username -e : 해당 유저의 crontab 수정

 

5. 목록 삭제

 

# crontab -r

 

6. 실행확인

 

# ps -ef | grep cron

 

7. 로그검토

 

# /var/log/cron

 

8. 파일 등록

 

# crontab [file_name]

 

9.시간 설정

 

 * * * * *

 1분 마다 수행

 5 * * * *

 매시 5분 마다 수행

 5 6 * * *

 매일 6시 5분에 수행

 5 6 7 * *

 매월 7일 6시 5분에 수행

 5 6 7 8 *

 매년 8월 7일 6시 5분에 수행

 5 6 * * 1

 매주 월요일 6시 5분에 수행

 5 6 1,10 * *

 매월 1일과 10일 6시 5분에 명령 수행

 5 6 1-10 * *

 매월 1일~10일 동안 6ㅛㅣ 5분에 명령 수행

 5 6 */5 * *

 매월 편집일로부터 5일마다 6시 5분에 수행

 

※ 주석 처리리시 맨 앞에 '#' 붙인다

   # * * * * * /usr/home/test.sh

 

※ PHP 쉘스크립트(php 바이너리 파일이 있는 곳을 앞에 적어준다)

 

 #!/usr/bin/php -e

<?php

    echo "hello";

?>

Posted by 다오나무
php2012. 7. 26. 19:23

//iframe 제거

 $STRING = preg_replace("!<iframe(.*?)<\/iframe>!is","",$STRING);
 

 //script 제거

 $STRING = preg_replace("!<script(.*?)<\/script>!is","",$STRING);
 

 //meta 제거

 $STRING = preg_replace("!<meta(.*?)>!is","",$STRING); 
 

 //style 태그 제거

 $STRING = preg_replace("!<style(.*?)<\/style>!is","",$STRING); 
 

 //&nbsp;를 공백으로 변환

 $STRING = str_replace("&nbsp;"," ",$STRING);
 

 //연속된 공백 1개로

 $STRING = preg_replace("/\s{2,}/"," ",$STRING);
 

 //태그안에 style= 속성 제거

 $STRING = preg_replace("/ style=([^\"\']+) /"," ",$STRING); // style=border:0... 따옴표가 없을때
 
$STRING = preg_replace("/ style=(\"|\')?([^\"\']+)(\"|\')?/","",$STRING); // style="border:0..." 따옴표 있을때
 

 //태그안의 width=, height= 속성 제거

 $STRING = preg_replace("/ width=(\"|\')?\d+(\"|\')?/","",$STRING);
 $STRING = preg_replace("/ height=(\"|\')?\d+(\"|\')?/","",$STRING);
 

 //img 태그 추출 src 추출

 preg_match("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$STRING,$RESULT);
 preg_match_all("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$STRING,$RESULT);

'php' 카테고리의 다른 글

파일 존재 여부 함수  (0) 2012.09.10
페이징 처리  (0) 2012.07.31
사이트 긁어오기  (0) 2012.07.25
snoopy class를 이용한 youtube 이미지 저장 (php)  (0) 2012.07.25
PHP5: Screen scraping with DOM and XPath  (0) 2012.07.24
Posted by 다오나무
php2012. 7. 24. 23:50

This tutorial is continuation from previous yahoo screen-scraping using PHP4 tutorial.
We will try different method using DOM and XPath which only supported in PHP5.

First, a bit knowledge of XPath is required. More about XPATH can be read on:

http://www.zvon.org/xxl/XPathTutorial/General/examples.html

Also there's small concern that using XPATH is a bit slower than pure DOM Traversal. Read Speed: DOM traversal vs. XPath in PHP 5
But i personally also think that XPath is neat and easier.

Let's start. First we diagnose document structure using Mozilla Firebug.
Try a very easy case, which is to grab the title "Top Movies":

Copy XPath using Firebug and get this query:

/html/body/center/table[8]/tbody/tr/td[5]/table[4]/tbody/tr/td/font/b

  1. Firefox automatically fix broken html structure, and it also add tbody tag. So, we need to remove this tag.
  2. Only grab first row of table. Change .../tr/td/font/b into .../tr[1]/td/font/b

Now we get our first XPath query:

/html/body/center/table[8]/tr/td[5]/table[4]/tr[1]/td/font

Next harder case is to grab contents.

XPath query from Firebug is:

/html/body/center/table[8]/tbody/tr/td[5]/table[4]/tbody/tr[2]/td[2]/a/font/b

  1. Same problem here. Firefox automatically fix broken html structure, and it also add tbody tag. Remove tbody tag from XPath query.
  2. Grab all row of table. Change .../tr[2]/td[2]/a/font/b into .../tr/td[2]/a/font/b

Final XPath query for content is:

/html/body/center/table[8]/tr/td[5]/table[4]/tr/td[2]/a/font/b

Now final step is to put all two XPath queries into few lines of code, and we're done:

PHP:
  1. <?php
  2.     error_reporting(E_ERROR);// | E_WARNING | E_PARSE);
  3.     include ('Snoopy.class.php');
  4.    
  5.     $snooper = new Snoopy();
  6.     if ($snooper->fetch('http://movies.yahoo.com/mv/boxoffice/')) {
  7.         $dom = new DomDocument();
  8.         $dom->loadHTML($snooper->results);
  9.        
  10.         $x = new DomXPath($dom);
  11.  
  12.         //  /html/body/center/table[8]/tbody/tr/td[5]/table[4]/tbody/tr/td/font/b
  13.         $nodes = $x->query('/html/body/center/table[8]/tr/td[5]/table[4]/tr[1]/td/font/b');
  14.         echo $nodes->item(0)->nodeValue"<br/>\n"//Top Movies
  15.  
  16.         //  /html/body/center/table[8]/tbody/tr/td[5]/table[4]/tbody/tr[2]/td[2]/a/font/b
  17.         $nodes = $x->query('/html/body/center/table[8]/tr/td[5]/table[4]/tr/td[2]/a/font/b');
  18.         foreach ($nodes as $node) {
  19.             echo $node->nodeValue"<br/>\n";
  20.         }
  21.     }
  22. ?>

Posted by 다오나무
php2012. 7. 24. 22:09

몇해전에 PHP 를 이용해서 멋진 라이브러리를 만든적이 있습니다.

아직도 애용하고 있죠 ㅎㅎ

웹페이지의 특정 정보를 얻기위해 로긴하고 게시물을 본다거나 글을 올리는 행위(?)를 꼭 브라우저를 쓰지않고 자동으로 동작하게 할수 없을까, 그리고 이걸 스케줄에 넣어서 자동화 할수 없을까 하다가 하나 만들게 된게 Autosurf 라는 php 라이브러리입니다.

당시에 잘 쓰지 않는 php 의 클래스를 써서리 멋지게 만들었지요.

그래서 무단 갈무리 해오기에 무척이나 좋게 되었고, 한때 유행하던 sms 보내는걸 제 홈피에 내가 서비스 하는것처럼 올릴수도 있었죠.

그당시 sms 가 무료라서 상당히 좋았었는데.. 지금은 유료화가 되서...

이걸 만들면서 http 통신 방식에 대해 많은걸 이해하게 되었답니다.


그 다음은 html 파서인데.. 이전에 펄(perl)을 좀 다루면서 펄에 내장 라이브러리로 있던 html 파서가 무척이나 마음에 들었는데.. 같은 방식으로 오히려 더 좋게 php 버전으로 만들었습니다.

html 태그 각 항목을 입맛대로 수정할수 있었지요.

autosurf 로 웹페이지를 가져온다음에 html파서로 정보 변경해서 제 홈피에 올리는 불펌.. 이랄까.. 그외에도 참 많이 애용 되고 있답니다.

Autosurf 소스 받기
autosurf.php 내용 보기
Html Parse 소스 받기


AutoSurf 1.0 Beta1

AutoSurf 는 자동으로 웹서핑을 할수 있는 프로그램입니다.
예들 들어 우리가 웹브라우저를 통해서 웹페이지를 서핑하는걸 프로그램으로
처리하는거지요.
쿠키/섹션을 이용한 인증처리도 통과가 가능합니다.
사용시에는 간단한 스크립터를 사용하면됩니다.

이걸 이용한다면, 문자메세지 전송프로그램도 제작가능하겠지요.
상대서버가 인증을 거치더라도 가능합니다.
특별한 경우를 제외하고는 자동웹서핑이 가능합니다.
특별한 경우라는건, 웹페이지가 자바스크립터를 이용해 쿠키세팅할때와
웹서버인증(입력폼이 뜨는..)에서는 아직 지원안합니다.

동작방식은, GET 과 POST 두개를 이용합니다.

라이브러리 사용법
require "autosurf.php";

$a = new autosurf();
$a->set_key("변수명", "값");
$a->set_key("변수명", "값");
$a->cfg_run("스크립터파일");


스크립터 명령어들..
debug: (yes/no) - http header 송신/수신을 보여줍니다. 가장상단에 한번적으시면 됩니다.
url: (domain) - 접속 주소
retry_num: (숫자) - 재전송 횟수. retry 명령어의 문자열을 만나면 재전송한다. form_action: (path 포함파일명) - 읽을 html 파일 혹은 디렉토리, http url은 제외 (

태그와 같음)
form_method: (get/post) - 메세지 전송양식( 태그와 같음) get 혹은 post
form_input: (key=value) - 파라메터 값전송( 태그화 같음)
show_html: (yes/no) - 전송받은 페이지 출력여부
retry: (문자열) - 결과 페이지 출력에 이 문자열을 만나면 재전송한다.


예제1)
# http://ping.dongman.pe.kr/new/main.php 로 접속한후 메세지를 보여줍니다.

- dongman.cfg 파일
debug: no

url: ping.dongman.pe.kr
form_action: /new/main.php
form_method: get
show_html: yes

- dongman.php 실행 프로그램
require "autosurf.php";

$a = new autosurf();
$a->cfg_run("dongman.cfg");

예제2)
# 라이코스를 통한 문자메세지 전송 스크립터 예제입니다.
아이디와 패스워드는 XXX 로 표현했습니다.
먼저 oneid.lycos.co.kr 로 접속하여 인증을 통과합니다.
debug: no 를 통해 http 헤더값을 출혁하지 않습니다.
각 url 접속시 show_html: yes 값을 주지않으면 페이지내용을 출력하지않습니다.
인증후 mobile-mail.lycos.co.kr 로 접속후 메세지를 전송합니다.
메세지 보낼시 [receiver], [recall1] 등등 괄호가 보이는건 변수입니다.

- lycos.cfg 스크립터 파일
debug: no

url: oneid.lycos.co.kr
form_action: /logon.jsp
form_method: post
form_input: LOGIN=YES
form_input: SOURCE=MMAIL
form_input: ID=XXXXX
form_input: PASSWD=XXXXX

url: mobile-mail.lycos.co.kr
form_action: /Korean/message/send_msg_final.asp
form_method: post
form_input: receiver=[receiver]
form_input: recall1=[recall1]
form_input: recall2=[recall2]
form_input: recall3=[recall3]
form_input: ResOrNot=soon
form_input: content=[content]
form_input: mycount=[mycount]
form_input: current_date=[current_date]
form_input: current_time=[current_time]
show_html: no 


- sms.php 실행 프로그램
require "autosurf.php";

$a = new autosurf();
$a->set_key("receiver", $sms_num1);
$a->set_key("recall1", $num1);
$a->set_key("recall2", $num2);
$a->set_key("recall3", $num3);
$a->set_key("content", $sms_message);
$a->set_key("mycount", strlen($sms_message));
$a->set_key("current_date", date("Ymd"));
$a->set_key("current_time", date("Hi"));
$a->cfg_run("lycos.cfg");

Posted by 다오나무
php2012. 7. 11. 13:47

$conn = mysqli_connect("localhost", "test", "test", "test");

 $conn->query("Create table test_model"."(year integer, model varchar(50), accel REAL)");

 $stmt = $conn->prepare("insert into test_model values(?,?,?)");
 $stmt->bind_param("isd", $year, $model, $accel);

 

 prepare 의 사전적 의미를 생각한다면 쉽게 이해할 수 있다.

 

 $stmt = $conn->prepare("insert into test_model values(?,?,?)");

 

 쿼리를 이렇게 날리겠다. 라는 의미라고 생각해도 무방할 듯 하다.

 $stmt->bind_param("isd", $year, $model, $accel);

 

 여기서는 컬럼이 총 3개인데 파라메타 값이 4개가 들어가 있다.

 

 첫 isd 를 제외하고는 나머지는 컬럼에 들어갈 값이라는 걸 쉽게 알 수 있다.

 

 isd를 잘 살펴 보면 의외로 답은 쉽게 나온다.

 

 i 의 경우는 integer 를 의미하고

 

s 의 경우는 문자(string)을 의미하고

 

d 의 경우는 double 형을 의미한다.

 

$year, $model, $accel 의 순서로 입력이 되니 첫번쨰 파라메터 역시 isd로 써주면 된다.

 

추가적으로 b 옵션이 하나 있는데 이것은 blob 형으로 들어간다고 메뉴얼에.. ㅡ,,ㅡ


/*
 $year = 2001;
 $model = '156 2.0 Selespeed';
 $accel = 8.6;
 $stmt->execute();

 $year= 2003;
 $model = '147 2.0 Selespeed';
 $accel = 9.3;
 $stmt->execute();

 $year = 2004;
 $model = '156 GTA Sportwagon';
 $accel = 6.3;
 $stmt->execute();
*/

마지막으로 위 주석으로 된 코드에 주석을 없애고 실행을 하면 디비에 잘 들어가 있는 것을

 

확인할 수 있다.

 

디비에서 가져올 경우는

 

 $conn = mysqli_connect("localhost", "test", "test", "test");

 $stmt = $conn->prepare("select * from test_model order by year");
 $stmt->execute();

 $stmt->bind_result($year, $model, $accel);

 echo "<table>\n";
 echo "<tr><th>model</th><th>0-100 km/h</th></tr>\n";

 while($stmt->fetch()){
  echo "<tr><td>$year $model</td><td>{$accel} sec</td>\n";
 }
 echo "</table>\n";

Posted by 다오나무
php2012. 7. 10. 13:03




· 이제 아는 정규식을 총동원해서 규칙을 생성해주시면 됩니다! 말은 무지 간단하네요^^;


//C:\CodeIgniter_2.1.0\system\libraries\Form_validation.php

    /**
     * Convert PHP tags to entities
     *
     * @access    public
     * @param    string
     * @return    string
     */

    public function encode_php_tags($str)
    {
        return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str);
    }
    
    public function alpha_number_kr($str) { //특수문자, 한글, 영문, 숫자
        return ( ! preg_match("/^([\+\.\:\-_ 가-힣a-zA-Z0-9])+$/i", $str)) ? FALSE : TRUE;
    }
    
    public function alpha_kr($str) { //한글, 영문
        return ( ! preg_match("/^([가-힣a-zA-Z])+$/i", $str)) ? FALSE : TRUE;
    }
    
    public function id($str) { //맨 앞글자 반드시 영문, 그 뒤 영문, 숫자, 특수문자
        return ( ! preg_match("/^([a-zA-Z]+[a-zA-Z0-9\-\_\.])+$/i", $str)) ? FALSE : TRUE;
    }
    
    public function zero($str) { //숫자 0
        return ( $str == '0') ? FALSE : TRUE;
    }
    
    public function blank($str) { //빈칸
        return ( isset($str)) ? FALSE : TRUE;
    }
    
    public function noCheck($str) { //not 'no'
        return ( $str != 'no') ? FALSE : TRUE;
    }

Posted by 다오나무
php2012. 7. 10. 12:55



Posted by 다오나무
영삼이의 IT정보2012. 6. 14. 11:17

방법1. number_format(값,자리수); 함수 사용

예---------------------------------------

코드.

<?

$char = 1234;

 echo number_format($char,2);

?>

 

실행 결과.

1,234.00

-----------------------------------------
1,234.00 이라는 소수점 두 자리까지의 처리 결과를 돌려 준다.

일반적으로 number_format() 함수는 숫자를 금액 단위로 표현하여

화면에 보여주려고 할 경우 많이 사용하는 함수입니다.

 

 

방법2. floor(); 함수 사용

예---------------------------------------

코드.

<?

$char = 1234.123;

$char2 = floor($char*10000))/100

 echo ($char2);

?>

 

실행 결과.

1234.12

-----------------------------------------

1234.123값을 123412.3으로 만든 다음 floor()함수를 써서 정수값만 가져온다.

그런다음 /100을 해서 소수점 두자리까지의 값을 가져온다.

Posted by 다오나무
영삼이의 IT정보2012. 5. 29. 13:05

PCRE 정규표현식 기본기


http://kr2.php.net/manual/en/ref.pcre.php
http://kr2.php.net/manual/en/reference.pcre.pattern.syntax.php
http://kr2.php.net/manual/en/reference.pcre.pattern.modifiers.php

위 링크의 내용을 바탕으로 기본을 설명합니다.

1. \ : 정규표현식에 사용되는 기호를 문자로써 사용하기 위해 탈출(escape) 시키는 문자.
<?php
preg_match('/\//', '---/---', $matches);
echo $matches[0];
?>
/

2. . : 아무거나 한 글자를 의미 (UTF-8 에서는 글자단위 그 외에는 byte 단위) (개행문자 제외)
3. ^ : 시작을 의미
<?php
echo preg_replace('/^./', '', 'abcd');
?>
bcd

4. $ : 끝을 의미
<?php
echo preg_replace('/.$/', '', 'abcd');
?>
abc

5. * : 앞의 기호의 반복을 의미 없어도 참
6. + : 앞의 기호의 반복을 의미 없으면 거짓
7. [] : [] 안의 내용 중 한글자를 의미 (- 로 구간설정 가능)
8. \d : [0-9] 를 의미
<?php
if(!preg_match('/^[1-9]\d*$/', $_GET['no'])) {
    echo '1 부터 시작하는 수를 적으셔';
    exit;
}
if(!preg_match('/^[a-z]+$/', $_GET['text'])) {
    echo '영문 소문자만 적으셔';
}
?>

9. \s : 공백문자를 의미 (탭 포함)
10. \t : 탭을 의미
11. \r : 개행문자 0x0d 를 의미
12. \n : 개행문자 0x0a 를 의미
<?php
$text = <<<TEXT
가나다 김삼순
킹왕짱     어쭈구리

abcd
TEXT;
print_r(preg_split('/[\s\r\n]+/', $text));
$text = <<<TEXT

?>
Array
(
     [0] => 가나다
     [1] => 김삼순
     [2] => 킹왕짱
     [3] => 어쭈구리
     [4] => abcd
)
<?php
$text = <<<TEXT
이름\t진\t선\t미
김태희\t80\t90\t100
송혜교\t100\t100\t98
TEXT;
$rows = preg_split('/[\r\n]+/', $text);
foreach($rows as $row) {
    $cols[] = preg_split('/\t/', trim($row));
}
print_r($cols);
?>
Array
(
     [0] => Array
         (
             [0] => 이름
             [1] => 진
             [2] => 선
             [3] => 미
         )

     [1] => Array
         (
             [0] => 김태희
             [1] => 80
             [2] => 90
             [3] => 100
         )

     [2] => Array
         (
             [0] => 송혜교
             [1] => 100
             [2] => 100
             [3] => 98
         )

)

13. ? : 존재유무 ()괄호와 함께 쓸 수 있다.
<?php
$text = <<<TEXT
<input type="text" name=asdf value="asdf" />
TEXT;
$cnt = preg_match_all('@([a-z]+)\s*=\s*"?([a-z]+)@', $text, $matches);
unset($matches[0]);
print_r($matches);
?>
Array
(
     [1] => Array
         (
             [0] => type
             [1] => name
             [2] => value
         )

     [2] => Array
         (
             [0] => text
             [1] => asdf
             [2] => asdf
         )

)
<?php
$text = <<<TEXT
<p>asdf <strong>zxcv</strong></p>
<p><strong>zxcv</strong> zxcv zxcv</p>
TEXT;
echo preg_replace('@(<strong>)?zxcv(</strong>)?@', 'qwer', $text);
?>
<p>asdf qwer</p>
<p>qwer qwer qwer</p>

14. .*?, .+? : 매치범위를 최소화 한다.
<?php
$text = <<<TEXT
<a href="a">a</a><a href="b">b</a><a href="c">c</a>
TEXT;
preg_match('@<a .*>@', $text, $matches);
echo $matches[0]."\n";
preg_match('@<a .*?>@', $text, $matches);
echo $matches[0]."\n";
?>
<a href="a">a</a><a href="b">b</a><a href="c">c</a>
<a href="a">

Posted by 다오나무
기타2012. 5. 21. 00:59




iPhone 에서 작성된 글입니다.

'기타' 카테고리의 다른 글

강남 파이낸스 빌딩 밤  (0) 2012.05.21
여의도 옥상  (0) 2012.05.21
marsEdit Test  (0) 2012.05.20
오 ecto 테스트중  (0) 2012.05.20
맨인블랙3  (0) 2012.05.19
Posted by 다오나무