php sandbox 굿

PHP/TIP 2011/09/28 12:24 Posted by <!--r'i"z&i\n+#]]x juree23
http://forums.theplanet.com/index.php?showtopic=59910
저작자 표시 비영리 변경 금지

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

php sandbox 굿  (0) 2011/09/28
memcached key가져오기~  (1) 2011/09/27
php로 html dom parsing을 아주 쉽게!  (0) 2011/09/27
phpunittest  (0) 2010/04/20
php autoload  (0) 2010/04/02
php에서 mysql사용법  (0) 2009/04/17

memcached key가져오기~

PHP/TIP 2011/09/27 18:06 Posted by <!--r'i"z&i\n+#]]x juree23
http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=74319


php version : 5.2.8
install : http://code.google.com/p/memcached/wiki/NewStart
          http://www.php.net/manual/en/memcache.installation.php


php.ini :
session.save_handler = memcache

source :
<?php
DEFINE ('MEM_HOST1','111.111.111.111');
DEFINE ('MEM_PORT', 11211);

$memcache = new Memcache;
$memcache->addServer(MEM_HOST1,MEM_PORT);

$list = array();
$i = 0;
$Slabs= $memcache->getExtendedStats('slabs');
$items = $memcache->getExtendedStats('items');
foreach ($Slabs as $server => $slabs) {
  foreach ($slabs as $slab_id => $slabMeta) {
    if(is_numeric($slab_id)){
      $cache_dump = $memcache->getExtendedStats('cachedump', (int)$slab_id);
      foreach ($cache_dump as $server => $entries) {
        if ($entries) {
          foreach ($entries as $entry => $detail) {
            $list[$entry] = array(
                'key' => $entry,
                'server' => $server,
                'slab_id' => $slab_id,
                'detail' => $detail,
                'age' => $items[$server]['items'][$slab_id]['age'],
                );
            if($memcache->get($entry)){
              $value[] = array($entry=>$memcache->get($entry));
              $key_list[] = $entry;
              $i++;
            }
          }
        }
      }
    }
  }
}
/*
print_r($list); 
print_r($value);
print_r($memcache->getVersion());
print_r($memcache->getStats());
print_r($memcache->getExtendedStats());
*/
echo "use memcache key count : ". $i."\n";
echo "Key List ";
print_r($key_list);

//아래는 memcache data가 session 일 경우 확인 하는 법
//$data = $memcache->get(session_id());
//print_r(unserialize($data));
/*  key value
foreach($key_list as $key){
  $data = $memcache->get($key);
  print_r($data);

}
*/
?>
저작자 표시 비영리 변경 금지

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

php sandbox 굿  (0) 2011/09/28
memcached key가져오기~  (1) 2011/09/27
php로 html dom parsing을 아주 쉽게!  (0) 2011/09/27
phpunittest  (0) 2010/04/20
php autoload  (0) 2010/04/02
php에서 mysql사용법  (0) 2009/04/17

php로 html dom parsing을 아주 쉽게!

PHP/TIP 2011/09/27 10:01 Posted by <!--r'i"z&i\n+#]]x juree23

개요

php에서 html파일을 string으로 읽어들여 dom parsing하려면, SimpleXML같은 extension을 이용해도 되겠지만, 사실 사용하기가 까칠하다. 그래서 찾아보던중 아주아주 간단한 라이브러리를 발견할 수 있었다.

PHP Simple HTML Dom Parser

  • php5로 작성되었음
  • invalid한 HTML도 지원함.
  • jQuery와 비슷한 셀렉터로 태그를 찾을 수 있음!
  • 한 줄로 html 파일 안의 컨텐츠를 뽑아올 수 있다.

Downloads & Documents

  • Sourceforge에서 최신 버전을 다운로드 가능하다.
  • 문서는 여기서 읽을 수 있다.

사용법

html 엘리먼트 가져오기

// url로부터 html을 읽어들임
$html = file_get_html('http://www.daum.net/');
 
// 모든 img태그를 찾는다.
foreach($html->find('img') as $element)
       echo $element->src . '<br>';
 
// 모든 링크를 찾는다.
foreach($html->find('a') as $element)
       echo $element->href . '<br>';

html 변경하기

$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
$html->find('div', 1)->class = 'bar';
$html->find('div[id=hello]', 0)->innertext = 'foo';
echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>

html의 내용을 태그 없이 읽어오기

// Dump contents (without tags) from HTML
echo file_get_html('http://www.google.com/')->plaintext;

Labels

Edit
저작자 표시 비영리 변경 금지

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

php sandbox 굿  (0) 2011/09/28
memcached key가져오기~  (1) 2011/09/27
php로 html dom parsing을 아주 쉽게!  (0) 2011/09/27
phpunittest  (0) 2010/04/20
php autoload  (0) 2010/04/02
php에서 mysql사용법  (0) 2009/04/17

phpunittest

PHP/TIP 2010/04/20 10:55 Posted by <!--r'i"z&i\n+#]]x juree23
http://kwon37xi.egloos.com/2935660
저작자 표시 비영리 변경 금지

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

memcached key가져오기~  (1) 2011/09/27
php로 html dom parsing을 아주 쉽게!  (0) 2011/09/27
phpunittest  (0) 2010/04/20
php autoload  (0) 2010/04/02
php에서 mysql사용법  (0) 2009/04/17
대단한 php, 동적 함수 접근 방법이란다~@_@  (0) 2008/06/27

php autoload

PHP/TIP 2010/04/02 17:51 Posted by <!--r'i"z&i\n+#]]x juree23
http://kangmaru.tistory.com/1
저작자 표시 비영리 변경 금지

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

php로 html dom parsing을 아주 쉽게!  (0) 2011/09/27
phpunittest  (0) 2010/04/20
php autoload  (0) 2010/04/02
php에서 mysql사용법  (0) 2009/04/17
대단한 php, 동적 함수 접근 방법이란다~@_@  (0) 2008/06/27
템플릿 클래스의 사용  (0) 2008/06/21

php에서 mysql사용법

PHP/TIP 2009/04/17 14:27 Posted by <!--r'i"z&i\n+#]]x juree23
<?
$dbId = "test";
$dbPassword = "12345";
$dbName = "test";

$conn = mysql_connect('localhost', $dbId, $dbPassword);

if (!$conn) {
die('Could not connect: ' . mysql_error());
}

$selectDB =  mysql_select_db($dbName, $conn);
if(!selectDB) {
echo("데이터베이스 에러");
exit;
}

//mysql_query("set character set euckr");

$query = "SELECT * FROM mem";
$result = mysql_query($query,$conn) or die("잘못된 퀴리문입니다");

while ($row = mysql_fetch_array($result)) {
    $num = $row["num"];
    $id = $row["id"];
    $name = $row["name"];
    $sex = $row["sex"];
    $tel = $row["tel"];
}
저작자 표시

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

phpunittest  (0) 2010/04/20
php autoload  (0) 2010/04/02
php에서 mysql사용법  (0) 2009/04/17
대단한 php, 동적 함수 접근 방법이란다~@_@  (0) 2008/06/27
템플릿 클래스의 사용  (0) 2008/06/21
알고있으면 유용한 PHP 환경변수  (0) 2008/06/21

대단한 php, 동적 함수 접근 방법이란다~@_@

PHP/TIP 2008/06/27 09:46 Posted by <!--r'i"z&i\n+#]]x juree23
<?php
class Foo { // Foo 클래스 선언
   
    public $aaa = "aaa"; // public 으로 $aaa 변수를 'aaa'로 초기화 (php5용: php4는 선언과 동시에 초기화 할수 없음)
   
    function setVar($a) {
        $this->{$a} = "zzz"; // $a에 들어있는 스트링을 변수이름 선언하고 zzz로 입력
       
    }   
   
    function out() {
        echo $this->foo; // foo 이름의 멤버변수를 출력
    }
}
$cc = 'Foo';
$foo = new $cc(); // $cc의 변수이름으로 된 클래스를 객체로 선언

$foo->setVar('foo'); // Foo 클래스의 setVar의 함수로 foo 값을 입력( 입력된 문자열이 객체의 멤버변수로 선언됨
$foo->out();  // 위에 선언된 foo 의 값으로 출력

$aa = 'out';
$foo->$aa();  // $cc의 변수이름으로 된 멤버함수를 실행
?>

간단요약
{$varname} 는 $varname변수의 이름으로 변수가 동적으로 생성 및 선언 될수 있음
$methodname = STRING; 는
$methodname(); 의 형식으로 변수값에 대한 함수이름을 참조하여 실행 할 수 있음

틀리면 고쳐주세요. *ㅡ*;;

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

php autoload  (0) 2010/04/02
php에서 mysql사용법  (0) 2009/04/17
대단한 php, 동적 함수 접근 방법이란다~@_@  (0) 2008/06/27
템플릿 클래스의 사용  (0) 2008/06/21
알고있으면 유용한 PHP 환경변수  (0) 2008/06/21
강력한 인증 - auth 인증 함수 소스  (0) 2008/06/21

템플릿 클래스의 사용

PHP/TIP 2008/06/21 16:52 Posted by <!--r'i"z&i\n+#]]x juree23
템플릿 클래스의 사용  

간단한  설명은  다음과  같습니다.  

먼저  기존의  코딩  방법  입니다.  

#  파일명  :  index.html  
 
 
for($i=0;$i=200;$i++)  
{  
         echo  "$i
";  
}  
?>  
 
 

식으로  제작  하였습니다.  이경우  위에  애기한  데로.  나중에  디자인  수정시에는  프로그래머와    디자인너가  작업을  둘이서  해야  했습니다,.  
Templite를  이요하면  다름과  같이  쓰여  집니다.  

#  파일명  :  index.html  
include("class.FastTemplate.php");  
$tpl  =  new  FastTemplate("./templates");  
$tpl->define(  
         array(  
         main        =>  "index.tpl",  
           )  
   );  
for($i=0;$i=200;$i++)  
{  
         $temp  .=  "$i
";  
}  


$tpl->assign(  array(  BODY  =>  "$temp")  );  
$tpl->parse(MAIN,  array("main"));  
$tpl->FastPrint();  
?>  
#  파일명  :  index.tpl  
 
 
{BODY}  
 
 

짠.!~  위처럼  2개의  화일을  생성  하게  됩니다.  
index.html  이  index.tpl  화일을  있어  드려  
{}  안에  BODY  라는  부분을  찾에  바꾸  다음에  
화면에  출력  하게  됩니다....  눈치  빠른  분은  이해  하셨겠죠.!  

이렇게  되면  간단하게  디자이너는  디자인을  수정  하고  싶을때  
index.tpl  화일만  고치고서  OverWrite하면  땡.땡.땡.  

쉽지  않습니다깡.  아주  간단한  애이기는  합니다만.  
이해가  쉬우실거라  믿습니다.  

이제는  우리가  게시판을  만드거나  할때  셀이  게속늘어  나게  됩니다.  
그럼  위철  ㅁ하면  좀  코드가  지저분스해지고  
셀  생상들을  바꾸때  참으로  힘들어  지겠죠  
하지만  Templite  안에는  그런  경우를  대비하여  관련  Function()을  만들어  놓았습니다.  

사용  예는  다음과  같습니당.  

#화일명  :  index.html  

include("../lib/class.FastTemplate.php");  
$tpl  =  new  FastTemplate("./");  
$tpl->define(array(main  =>  "index.tpl"));  
$tpl->define_dynamic(row,main);  
//  DB의  자료들을  Row에  반영하며  처리  
if($all  >  0)  
{  
for($i=0;$i<$all;$i++)  
{  
         $row  =  $result_db->fetch_row($this->result,1);  
$no  =  $i+1;  
$tpl->assign(array(  
       NO  =>  $no,  
       NAME  =>  $name,  
       TEL  =>  $row[2],  
       HP  =>  $row[3],  
       EMAIL  =>  $row[5],  
$tpl->parse(ROWS,  ".row");  
}  
}else  
{  
$tpl->clear_dynamic(row);  
}  

$tpl->parse(MAIN,  array("main"));  
$tpl->FastPrint();  
exit;  
?>  

#파일명  :  index.tpl  

     
     
       {NO}  
        {NAME}  
        {TEL}  
        {HP}  
     
     


간단히  이렇게  하면  게시판  형태  역시  간단히  해결  됩니다.  

지면이  작고  넘  길게  쓰면  진호님이  뭐라고  할까봐서  
줄입니다  

주로  쓰여지는  부분만  넣어  놓았습니다.  
이제는  여러분이  직접  해보는  일입니다.  

해당  클래스는  다음의  사이트에  있습니다.  

http://www.thewebmasters.net/php/FastTemplate.phtml  

잠깐.!  위의  것을  php3  에  맞추어  져  있습니다  

PHP4의  경우는  아래와  같이  몇개  부분을  고치셔야  잘  나옵니당.  

//$template  =  ereg_replace("{$key}","$val","$template");  
//$template  =  str_replace("$key","$val","$template");  


위  두줄을  주석  처리하고  아래의  두  줄을  추가  

$key  =  '{'."$key".'}';  
$template  =  ereg_replace("$key","$val","$template");  

//$newParent  .=  "{$MacroName}\n";  

위와  돌일하게  위  줄을  찾아서  아래의  줄로  변경  

$newParent  .=  '{'."$MacroName}\n";  

자  이제  여러분이  직접  만들어  보시면  됩니당.  
제가  이번에  대기업  프로그램  제작  사에도  사용하였습니다.  

전혀  문제  없이  작동  됩니다.  

좀더  더  많은  자료를  요구  하시면  

http://www.phpclass.com  

로  가시면  자세한  설명과  주인이  만든  클래스  들도  있심당.  

자료가  더  필요하시무눈의  thewebmaster  로  가시거나  
아님  메일  주세요  
화일이랑  Sample이랑  보내  드릴꼐용.   

알고있으면 유용한 PHP 환경변수

PHP/TIP 2008/06/21 16:50 Posted by <!--r'i"z&i\n+#]]x juree23
알고있으면 유용한 PHP 환경변수  

URL  :  /html/test?id=aa&passwd=bb

$PHP_SELF  :  /html/test

$REQUEST_URI  :  /html/test?id=aa&passwd=bb

$QUERY_STRING  :  넘어온  변수들만  저장  id=aa&passwd=bb

$SERVER_NAME  :  www.servername.co.kr  이  들어있다..  

$SERVER_ADMIN  :  admin_id@userhost.co.kr  이  들어있슴..  

$REMOTE_ADDR  :  현재의  클라이언트의  ip

$HTTP_COOKIE  :  현재의  쿠키정보저장  ex,  email=bellheat;  name=aaaa  

$HTTP_COOKIE_VARS["쿠키변수이름"]  :  쿠키변수의  값을  저장

$HTTP_USER_AGENT  :  클라이언트  정보

$REQUEST_METHOD  :  GET  or  POST

강력한 인증 - auth 인증 함수 소스

PHP/TIP 2008/06/21 16:46 Posted by <!--r'i"z&i\n+#]]x juree23

md5() 암호화 하시구요..아래는 간단한 예제 입니다.

보안에는 auth 인증이 가장 좋습니다.

auth 인증 > 세션 >>> 쿠키

입니다.


<?PHP

$username = "test";
$password = "123";

function authenticate() {
Header( "WWW-authenticate: basic realm=\"왕국\"");
Header( "HTTP/1.0 401 Unauthorized");
echo "아뒤와 패스 워드를 넣어야 한다.!\n";
exit;
}

function CheckPwd($user,$pass) {
global $username,$password;
return ($user != $username || $pass != $password) ? false : true;
}

if(!isset($PHP_AUTH_USER)) {
authenticate();
}
elseif(!CheckPwd($PHP_AUTH_USER,$PHP_AUTH_PW)) {
authenticate();
}
?>

<html>
<head>
<title>auth 인증 시스템 </title>
</head>
<body bgcolor="#FFFFFF">
<font face="Verdana, Arial" size="2"><b>환영해요 !</b></font>
<hr size="1" width="300" align="left">
<font face="Verdana, Arial" size="2">인증 성공 !</font>
</body>
</html>

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

▧ PHP Auth ( php HTTP 인증 ) ▧
Basic HTTP authentication uses a challenge/response scheme to authenticate users attempting to access a
password-protected page. The challenge process begins when the user requests a file from a Web server.
If the file is within a protected area, the server responds by sending out a 401 (unauthorized user)
string in the header of the response. The browser detects that response and up pops the
username/password dialog box. The user enters a username and password in the dialog box, then clicks OK
to send the information back to the server for authentication.

번역 및 해설 : 투덜즈 suhoi@naver.com
저작권 : 전혀 저작권과 상관 없슴다. 터터 ^^;


★ 원리 및 사용 ★
사용자가 웹서버에 접속 함다. 글구 마구 마구 돌아 댕기죵 ^^
근디 웹서버 는 감추고 싶은곳이 있습니다. 일명 보안 구역 이라고 하죵^^

/*
남자에게도 감추고 싶은 비밀이 있답니다.
그때 여자가 접근해오면 401 노(No) 인증 메시지를 뿌리고 암호를 확인 하죵^^
*/


그때 사용자가 보안 구역에 접속을 시도하면 401 인증 되지 않았다는 http
인증 메시지를 사용자 브라우져에 보냅니다.

물론 그전에 로그인을 했으면 보내지 않습니다.
로그인 창에 아뒤와 패스워드를 넣으라는 메시지를 보냅니다.

그래서 사용자가 맞으면 보여주고 맞지 않으면 보여주지 않습니다.

주의.
1. http 인증은 반드시 php 가 모듈로 컴파일된 상태에서만 가능 함다.
2. header() 는 echo 보다 앞에 와야 함다.
3. logout 할려면 브라우져 는 죽여야 함다.( 종료 )
[ 브라우져를 죽이지 않는한 유저아뒤와 비번은 계속 살아 있슴다.]


$PHP_AUTH_USER : http 인증창으로 들어온 유저 아뒤
$PHP_AUTH_PW : 패스워드

다음은 유저아뒤와 계정을 데이터 베이스에 만들어 놓고 , 보호구역에 당도하면
http 인증을 보내서 , 값을 받았으면 그 값과 데이터 베이스에 있는 값과
비교 하는 프로그램 입니다.

★ 해보시지 않으면 먼 내용인지 모르니 반드시 해보십시오.
★ 유저 아뒤와 비번 을 넣은 테이블은 반드시 맹그십시오.

mysql> create table suhoi (
> username char(10),
> password char(10));



☞ auth2.php3
----------------------------------------------------------------

<?
// made by suhoi@naver.com
// http://myhome.naver.com/suhoi ;

if (!isset($PHP_AUTH_USER)) {

// header() 에 의해 WWW-Auth 와 HTTP 인증 메시지를 보낸다.
header('WWW-Authenticate: Basic realm="My Suhoi kingdom"');
header('HTTP/1.0 401 Unauthorized');
echo '유저아뒤와 비번이 반드시 필요하다';
exit;

} else {

$connection = mysql_connect("hostname", "username", "password")
or die ("Couldn't connect to server.");

$db = mysql_select_db("database_name", $connection)
or die ("Couldn't select database.");

$sql = "SELECT username
FROM suhoi
WHERE username='$PHP_AUTH_USER'
and password='$PHP_AUTH_PW'";

$result = mysql_query($sql)
or die("Couldn't execute query.");

$num = mysql_numrows($result);

if ($num == 1) {

echo "<P>환영합니다.<br>";
echo "당신의 아뒤는 $PHP_AUTH_USER 이다.<br>";
echo "당신의 비번은 $PHP_AUTH_PW 이다.</p>";

} else if ($num == 0) {

echo "너의 아뒤와 비번은 틀렸당.";

}

}

?>

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

템플릿 클래스의 사용  (0) 2008/06/21
알고있으면 유용한 PHP 환경변수  (0) 2008/06/21
강력한 인증 - auth 인증 함수 소스  (0) 2008/06/21
PHP에서 특정 아이피 차단하기  (0) 2008/06/21
콘솔 채팅 프로그래밍  (0) 2008/06/21
Programming with NuSOAP Using WSDL  (0) 2008/06/16

PHP에서 특정 아이피 차단하기

PHP/TIP 2008/06/21 16:43 Posted by <!--r'i"z&i\n+#]]x juree23
if(eregi("xxx.xxx.xxx.xxx","$REMOTE_ADDR")) {
echo "접근할 수 없는 아이피입니다."; exit;
}

쉽죠?? php를 하시는분들은 다 아시리라 믿습니다.

eregi는 특정 형식에 맞는지 검사하는 함수고요...사용형식은

int eregi (string pattern, string string [, array regs])

요롷게 씁니다.

$REMOTE_ADDR은 아시죠? 접속 환경에서 IP 입니다.

IP가 xxx.xxx.xxx.xxx 라면 echo를 출력하고 빠져버리는거죠.

아 쉽다~

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

템플릿 클래스의 사용  (0) 2008/06/21
알고있으면 유용한 PHP 환경변수  (0) 2008/06/21
강력한 인증 - auth 인증 함수 소스  (0) 2008/06/21
PHP에서 특정 아이피 차단하기  (0) 2008/06/21
콘솔 채팅 프로그래밍  (0) 2008/06/21
Programming with NuSOAP Using WSDL  (0) 2008/06/16

콘솔 채팅 프로그래밍

PHP/TIP 2008/06/21 16:37 Posted by <!--r'i"z&i\n+#]]x juree23

콘솔 채팅 프로그램입니다. 테스트는 php 4.2.1 + Alzza 6.2에서 했습니다. 별 대
단한 기능이 있는 채팅 프로그램은 아니고 그냥 소켓 프로그램 예제 정도로 쓰면
좋은 정도입니다. socket_select, pcntl_fork 등의 함수를 사용하기 때문에 php 컴
파일 시에 enable-socket, enable-pcntl 옵션을 줘야 합니다.

-----------------------------------
1. Server.

#!/usr/bin/php
//-----------------------
class Select{
       var $fhs;
       
       //-----------------------
       function Select(&$fh){
               $this->fhs = array($fh);
       }

       //-----------------------
       function add(&$fh){
               array_push($this->fhs, $fh);
       }

       //-----------------------
       function remove(&$fh){
               for($i = 0; $i < count($this->fhs); $i++){
                       if($this->fhs[$i] == $fh){
                               array_splice($this->fhs, $i, 1);
                               break;
                       }
               }
       }

       //-----------------------
       function can_read($limit = 5){
               $read_fhs = $this->fhs;
               socket_select($read_fhs, $write_fhs = null, $exception_fhs = null, $limit);
               return $read_fhs;
       }

       //-----------------------
       function can_write($limit = 0){
               $write_fhs = $this->fhs;
               socket_select($read_fhs = null, $write_fhs, $exception_fhs = null, $limit);
               return $write_fhs;
       }
}

//-----------------------
class Guest{
       var $fh;
       var $name;

       function Guest($fh, $name){
               $this->fh = $fh;
               $this->name = $name;
       }
}

//-----------------------
class Lobby{
       var $fh;
       var $sel;
       var $guests;

       //-----------------------
       function Lobby(){
               $this->guests = array();
       }
       
       //-----------------------
       function open($addr, $port){
               $this->fh = socket_create(AF_INET, SOCK_STREAM, 0)
                       or die("create error!!n");
               socket_setopt($this->fh, SOL_SOCKET, SO_REUSEADDR, 1)
                       or die("setopt error!!n");
               socket_bind($this->fh, $addr, $port) or die("bind error!!n");
               socket_listen($this->fh, 5) or die("listen error!!n");

               $this->sel = new Select($this->fh);

               print "Wating...n";
       }

       //-----------------------
       function close($g){
               socket_close($this->fh);
       }

       //-----------------------
       function work(){
               while(true){
                       foreach($this->sel->can_read() as $fh){
                               if($fh == $this->fh){
                                       print "Got connection.n";
                                       $new = socket_accept($this->fh)
                                               or die("accept error!!n");
                                       $this->sel->add($new);
                                       socket_write($new, "## Input your name: ##n");
                               }
                               else{
                                       $buf = socket_read($fh, 1024);
                                       if($buf){
                                               printf("Received: %sn", $buf);
                                               $g = $this->get_guest($fh);
                                               if(! $g){
                                                       $this->add_guest(new Guest($fh
                                                               , $buf));
                                                       continue;
                                               }

                                               $this->talk2all(sprintf("%s: %sn"
                                                       , $g->name, $buf));
                                       }
                                       else{
                                               if($this->is_guest($fh))
                                                       {$this->del_guest($fh);}
                                               $this->sel->remove($fh);
                                               socket_close($fh);
                                               print "A client has been removed.n";
                                       }
                               }
                       }
               }
       }

       //-----------------------
       function talk2all($buf){
               foreach($this->guests as $g){
                       socket_write($g->fh, $buf);
               }
       }

       //-----------------------
       function get_guest(&$fh){
               for($i = 0; $i < count($this->guests); $i++){
                       if($fh == $this->guests[$i]->fh){return $this->guests[$i];}
               }
               return null;
       }

       //-----------------------
       function is_guest(&$fh){
               for($i = 0; $i < count($this->guests); $i++){
                       if($fh == $this->guests[$i]->fh){return true;}
               }
               return false;
       }

       //-----------------------
       function add_guest(&$g){
               array_push($this->guests, $g);
               $this->talk2all("## " . $g->name . " has entered. ##n");
               printf("count($this->guests) = %dn", count($this->guests));
       }

       //-----------------------
       function del_guest(&$fh){
               for($i = 0; $i < count($this->guests); $i++){
                       if($fh == $this->guests[$i]->fh){array_splice($this->guests, $i);}
               }
               printf("count($this->guests) = %dn", count($this->guests));
       }
}

//-----------------------
//main
set_time_limit(0);

$lob = new Lobby();
$lob->open("127.0.0.1", 8040);
$lob->work();
?>


-----------------------------------
2. Client.

#!/usr/bin/php
set_time_limit(0);

$fh = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
       or die("create error!!n");
socket_connect($fh, "127.0.0.1", 8040) or die("connect error!!n");

$pid = pcntl_fork();
if($pid == -1){die("could not fork");}

if($pid == 0){
       while(true){
               $in = fopen("php://stdin", "r");
               $line = fgets($in, 255);
               $line = trim($line);
               if($line){socket_write($fh, $line);}
       }
}
else{
       while(true){
               print socket_read($fh, 1024);
       }
}
?>

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

템플릿 클래스의 사용  (0) 2008/06/21
알고있으면 유용한 PHP 환경변수  (0) 2008/06/21
강력한 인증 - auth 인증 함수 소스  (0) 2008/06/21
PHP에서 특정 아이피 차단하기  (0) 2008/06/21
콘솔 채팅 프로그래밍  (0) 2008/06/21
Programming with NuSOAP Using WSDL  (0) 2008/06/16

Programming with NuSOAP Using WSDL

PHP/TIP 2008/06/16 19:05 Posted by <!--r'i"z&i\n+#]]x juree23
출처 : http://mirrh.com/board/view.php?&id=blog&no=44
-----------------------------------------------------------------
Programming with NuSOAP Using WSDL
NuSOAP is a group of PHP classes that allow developers to create and consume SOAP web services. It does not require any special PHP extensions. The current release version (0.6.7) of NuSOAP at the time this was written (03-November-2004), supports much of the SOAP 1.1 specification. It can generate WSDL 1.1 and also consume it for use in serialization. Both rpc/encoded and document/literal services are supported. However, it must be noted that NuSOAP does not provide coverage of the SOAP 1.1 and WSDL 1.1 that is as complete as some other implementations, such as .NET and Apache Axis.
This document follows up Introduction to NuSOAP, Programming with NuSOAP, and Programming with NuSOAP Part 2 with additional samples that demonstrate how to use NuSOAP to create and consume SOAP web services using WSDL.
Hello, World Redux
The New Client
Defining New Data Structures

Hello, World Redux

Showing no imagination whatsoever, I used the ubiquitous "Hello, World" example in Introduction to NuSOAP. In that document, I showed the SOAP request and response exchanged by the client and server. Here, I extend that sample to use WSDL.
A WSDL document provides metadata for a service. NuSOAP allows a programmer to specify the WSDL to be generated for the service programmatically using additional fields and methods of the soap_server class.
The service code must do a number of things in order for correct WSDL to be generated. Information about the service is specified by calling the configureWSDL method. Information about each method is specified by supplying additional parameters to the register method. Service code for using WSDL is shown in the following example.
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
$server->configureWSDL('hellowsdl', 'urn:hellowsdl');
// Register the method to expose
$server->register('hello',                // method name
array('name' => 'xsd:string'),        // input parameters
array('return' => 'xsd:string'),      // output parameters
'urn:hellowsdl',                      // namespace
'urn:hellowsdl#hello',                // soapaction
'rpc',                                // style
'encoded',                            // use
'Says hello to the caller'            // documentation
);
// Define the method as a PHP function
function hello($name) {
return 'Hello, ' . $name;
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
Now for some magic. Point a Web browser at this service, which in my environment is at http://localhost/phphack/hellowsdl.php. The HTML that is returned to your browser gives you links to view the WSDL for the service or view information about each method, in this case the hello method. The screen should look something like this.


So, with just a little code added to the service, NuSOAP provides browsable documentation of the service. But, that is not all. By either clicking the WSDL link on the documentation page, or by pointing the browser at the service with a query string of ?wsdl (e.g. http://localhost/phphack/hellowsdl.php?wsdl), you get the following WSDL.
<?xml version="1.0"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:si="http://soapinterop.org/xsd"
xmlns:tns="urn:hellowsdl"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="urn:hellowsdl">
<types>
<xsd:schema targetNamespace="urn:hellowsdl">
<xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
<xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
</xsd:schema>
</types>
<message name="helloRequest">
<part name="name" type="xsd:string" />
</message>
<message name="helloResponse">
<part name="return" type="xsd:string" />
</message>
<portType name="hellowsdlPortType">
<operation name="hello">
<documentation>Says hello to the caller</documentation>
<input message="tns:helloRequest"/>
<output message="tns:helloResponse"/>
</operation>
</portType>
<binding name="hellowsdlBinding" type="tns:hellowsdlPortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="hello">
<soap:operation soapAction="urn:hellowsdl#hello" style="rpc"/>
<input>
<soap:body use="encoded" namespace="urn:hellowsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body use="encoded" namespace="urn:hellowsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</output>
</operation>
</binding>
<service name="hellowsdl">
<port name="hellowsdlPort" binding="tns:hellowsdlBinding">
<soap:address location="http://localhost/phphack/hellowsdl.php"/>
</port>
</service>
</definitions>
Return to top.

The New Client

Adding a few NuSOAP WSDL calls to the service allows it to generate WSDL and other documentation. By comparison, client support for WSDL is anti-climactic, at least for this simple example. The simple client shown below is not much different than the non-WSDL client. The only difference is that the constructor for the soapclient class is provided the URL of the WSDL, rather than the service endpoint.
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the client instance
$client = new soapclient('http://localhost/phphack/hellowsdl.php?wsdl', true);
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
// At this point, you know the call that follows will fail
}
// Call the SOAP method
$result = $client->call('hello', array('name' => 'Scott'));
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
// Display the request and response
echo '<h2>Request</h2>';
echo '<pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2>';
echo '<pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
// Display the debug messages
echo '<h2>Debug</h2>';
echo '<pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
?>
Here are the request and response for this WSDL implementation.
POST /phphack/hellowsdl.php HTTP/1.0
Host: localhost
User-Agent: NuSOAP/0.6.8 (1.81)
Content-Type: text/xml; charset=ISO-8859-1
SOAPAction: "urn:hellowsdl#hello"
Content-Length: 550

<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:si="http://soapinterop.org/xsd"
xmlns:tns="urn:hellowsdl">
<SOAP-ENV:Body>
<tns:hello xmlns:tns="urn:hellowsdl">
<name xsi:type="xsd:string">Scott</name>
</tns:hello>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Wed, 03 Nov 2004 21:05:34 GMT
X-Powered-By: ASP.NET
X-Powered-By: PHP/4.3.4
Server: NuSOAP Server v0.6.8
X-SOAP-Server: NuSOAP/0.6.8 (1.81)
Content-Type: text/xml; charset=ISO-8859-1
Content-Length: 551

<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:si="http://soapinterop.org/xsd">
<SOAP-ENV:Body>
<ns1:helloResponse xmlns:ns1="urn:hellowsdl">
<return xsi:type="xsd:string">Hello, Scott</return>
</helloResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Return to top.

Defining New Data Structures

An important aspect of WSDL is that it can encapsulate one or more XML Schema, allowing programmers to describe the data structures used by a service. To illustrate how NuSOAP supports this, I will add WSDL code to the SOAP struct example in Programming with NuSOAP Part 2.
The service code gains the changes already shown in the Hello, World example, but it also has code to define the Person data structure.
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
$server->configureWSDL('hellowsdl2', 'urn:hellowsdl2');
// Register the data structures used by the service
$server->wsdl->addComplexType(
'Person',
'complexType',
'struct',
'all',
'',
array(
'firstname' => array('name' => 'firstname', 'type' => 'xsd:string'),
'age' => array('name' => 'age', 'type' => 'xsd:int'),
'gender' => array('name' => 'gender', 'type' => 'xsd:string')
)
);
$server->wsdl->addComplexType(
'SweepstakesGreeting',
'complexType',
'struct',
'all',
'',
array(
'greeting' => array('name' => 'greeting', 'type' => 'xsd:string'),
'winner' => array('name' => 'winner', 'type' => 'xsd:boolean')
)
);
// Register the method to expose
$server->register('hello',                    // method name
array('person' => 'tns:Person'),          // input parameters
array('return' => 'tns:SweepstakesGreeting'),    // output parameters
'urn:hellowsdl2',                         // namespace
'urn:hellowsdl2#hello',                   // soapaction
'rpc',                                    // style
'encoded',                                // use
'Greet a person entering the sweepstakes'        // documentation
);
// Define the method as a PHP function
function hello($person) {
$greeting = 'Hello, ' . $person['firstname'] .
'. It is nice to meet a ' . $person['age'] .
' year old ' . $person['gender'] . '.';

$winner = $person['firstname'] == 'Scott';

return array(
'greeting' => $greeting,
'winner' => $winner
);
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
Besides the additional code to support WSDL, the code for the service method itself is changed slightly. With WSDL, it is no longer necessary to use the soapval object to specify the name and data type for the return value.
Similarly, the WSDL client does not need to use a soapval to specify the name and data type of the parameter, as shown in the following code.
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the client instance
$client = new soapclient('http://localhost/phphack/hellowsdl2.php?wsdl', true);
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
// At this point, you know the call that follows will fail
}
// Call the SOAP method
$person = array('firstname' => 'Willi', 'age' => 22, 'gender' => 'male');
$result = $client->call('hello', array('person' => $person));
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
// Display the request and response
echo '<h2>Request</h2>';
echo '<pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2>';
echo '<pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
// Display the debug messages
echo '<h2>Debug</h2>';
echo '<pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
?>
WSDL enables one more capability on the client. Instead of using the call method of the soapclient class, a proxy can be used. The proxy is a class that mirrors the service, in that it has the same methods with the same parameters as the service. Some programmers prefer to use proxies because the code reads as method calls on object instances, rather than invocations through the call method. A client that uses a proxy is shown below.
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the client instance
$client = new soapclient('http://localhost/phphack/hellowsdl2.php?wsdl', true);
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
// At this point, you know the call that follows will fail
}
// Create the proxy
$proxy = $client->getProxy();
// Call the SOAP method
$person = array('firstname' => 'Willi', 'age' => 22, 'gender' => 'male');
$result = $proxy->hello($person);
// Check for a fault
if ($proxy->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $proxy->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
// Display the request and response
echo '<h2>Request</h2>';
echo '<pre>' . htmlspecialchars($proxy->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2>';
echo '<pre>' . htmlspecialchars($proxy->response, ENT_QUOTES) . '</pre>';
// Display the debug messages
echo '<h2>Debug</h2>';
echo '<pre>' . htmlspecialchars($proxy->debug_str, ENT_QUOTES) . '</pre>';
?>
Regardless of whether the "regular" or proxy coding style is used, the request and response messages are the same.
POST /phphack/hellowsdl2.php HTTP/1.0
Host: localhost
User-Agent: NuSOAP/0.6.8 (1.81)
Content-Type: text/xml; charset=ISO-8859-1
SOAPAction: "urn:hellowsdl2#hello"
Content-Length: 676

<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:si="http://soapinterop.org/xsd"
xmlns:tns="urn:hellowsdl2">
<SOAP-ENV:Body>
<tns:hello xmlns:tns="urn:hellowsdl2">
<person xsi:type="tns:Person">
<firstname xsi:type="xsd:string">Willi</firstname>
<age xsi:type="xsd:int">22</age>
<gender xsi:type="xsd:string">male</gender>
</person>
</tns:hello>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Wed, 03 Nov 2004 21:20:44 GMT
X-Powered-By: ASP.NET
X-Powered-By: PHP/4.3.4
Server: NuSOAP Server v0.6.8
X-SOAP-Server: NuSOAP/0.6.8 (1.81)
Content-Type: text/xml; charset=ISO-8859-1
Content-Length: 720

<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:si="http://soapinterop.org/xsd"
xmlns:tns="urn:hellowsdl2">
<SOAP-ENV:Body>
<ns1:helloResponse xmlns:ns1="urn:hellowsdl2">
<return xsi:type="tns:SweepstakesGreeting">
<greeting xsi:type="xsd:string">
Hello, Willi. It is nice to meet a 22 year old male.
</greeting>
<winner xsi:type="xsd:boolean">0</winner>
</return>
</helloResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

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

템플릿 클래스의 사용  (0) 2008/06/21
알고있으면 유용한 PHP 환경변수  (0) 2008/06/21
강력한 인증 - auth 인증 함수 소스  (0) 2008/06/21
PHP에서 특정 아이피 차단하기  (0) 2008/06/21
콘솔 채팅 프로그래밍  (0) 2008/06/21
Programming with NuSOAP Using WSDL  (0) 2008/06/16