urlencode() / urldecode():
하나의 특수문자, 한글, multi-byte 문자를 %XX 형식으로 변환합니다. 길이가 좀 길어진다는게 단점입니다. 또한 [0-9a-zA-Z] 등은 encode 하지 않아 그대로 보인다는 단점(?) 도 있습니다.
보안성이 없거나 크게 요구되지 않는 경우나 일반적으로 많이 사용하는 방법이며, URL GET 방식으로 어떤 값을 넘길때도 많이 사용됩니다.


base64_encode() / base64_decode()
변환된 문자는 [0-9a-zA-Z+/=] 문자들로 구성되어지며 역시 약간 길이가 길어집니다.
쉽 게 눈으로 판독(decode)할 수 없다는 장점(?)도 있습니다. 저수준의 보안성이 요구될때 사용하는 경우가 많습니다. URL GET 방식으로 어떤 값을 넘길때도 사용되지만 약간의 문제점이 있습니다.(+, / 문자 처리 문제, 아래 참고)


serialize() / unserialize()
이 함수는 어떤 특정 변수(variable)의 형태를 그대로 유지하면서 하나의 문자열로 변환합니다. 실제 본문의 문자열은 다른 형태로 변환되지 않으며, 다만 변수 형태를 유지하기 위해서 특정 형태의
문자열들이 붙습니다.
이 경우는 보통, 1차원 또는 다차원 배열을 하나의 문자열로 만들어 마치 하나의 문자열 변수처럼 취급하고자 할 경우에 많이 사용합니다. (쿠키나 세션 또는 파일저장 등에 많이 사용됨)
역시 URL GET 방식으로도 사용될 수 있지만 약간의 문제점이 있습니다.
(+, /, &, ?, # 등등 특수문자나 multi-byte 문자 처리 문제)


user_encode() / user_decode()
GET 방식등으로 어떤 값을 넘길 경우, 비교적 보안성이 요구될때 이런 사용자 정의 함수에 의해서 단방향이 아닌 쌍방향 함수를 이용하는 방법을 말합니다.
이때는 비밀키가 노출되면 안되겠죠...


이렇게 약간씩 그 쓰임새가 다르기 때문에 상황에 따라 적절한 방법을 선택하여 사용하면 됩니다.

*주의)
base64_encode() 로 변환된 문자열을 곧바로 GET 방식으로 넘기면 약간 문제점이 있습니다.

즉, '+' 문자와 '/' 문자인데, 값을 받을 때 '+'를 '+' 자체가 아닌 공백(%20)으로 인식하는 경우가 있습니다. (PHP 버전 문제아니면, 특이한 USER_AGENT 해석의 차이인듯)
(공백 ' '(%20)을 urlencode 하면 '+' 가 되죠)

따라서 '+' 를 다른 문자(?,/,#,&등은 절대 금물)나 문자열로 교체해줘야 합니다.
또한 '/' 문자도 디렉토리 구분이나 PATH_INFO 의 구분으로 인식할 수 있으므로 (PATH_INFO 로 구분하여 값을 받을 경우)역시 적절한 문자나 문자열로 교체해줘야 합니다.


*정리하면)
문자열(또는 특정 변수의 문자열 형태)을 URL GET 방식으로 넘길때 조심해야할 문자가 있습니다.
즉,
(공백), +, ?, #, &, / 등입니다.

(공백) : 이하를 해석하지 못하는 USER_AGENT 가 있을 수 있음
+ : 공백으로 해석 또는 인식되는 경우가 있음
? : 이하 쿼리로 인식됨
# : 이하 문자를 fragment 로 인식될 수 있음
& : 쿼리의 구분으로 인식될 수 있음
/ : PATH_INFO 로 구분한다면 하나의 path 로 인식되지 않음

이런 점만 주의한다면 어느 함수를 사용하든지 상관없겠죠(보안성 문제 제외).

이런 문자 처리를 자동(?)으로 처리해주는게 urlencode() 함수이며, 문자열 보안성은 결여되어 있습니다.

따라서, 이런 관점에서, 단독적인 base64_encode() 나 serialize() 함수는 URL GET 방식에 적합하지 않습니다.

Posted by 철냄비짱
,

rawurlencode

PHP 2008. 10. 30. 11:23

본 자료는 오토셋개발자그룹(www.autoset.org)에서 PHP 그룹(www.php.net)의 자료를 복사한 것으로 2006-12-01 09:48를 기준으로 작성되었습니다.

rawurlencode

(PHP 3, PHP 4 , PHP 5)

rawurlencode -- RFC 1738에 따라 URL을 인코드합니다.

설명

string rawurlencode ( string str)

-_.을 제외한 모든 영숫자가 아닌 문자를 퍼센트(%) 사인에 이어지는 두 16진수로 교체한 문자열을 반환합니다. 이는 표시 문자가 특별한 URL 구분자로 해석되는걸 방지하고, 문자 변환이 이루어지는 전송 매체(몇몇 email 시스템 등)에서 URL을 보호하기 위한 RFC 1738에 설명된 인코딩입니다. 예를 들어, FTP URL에 패스워드를 포함하고자 한다면:

예 1. rawurlencode() 예제 1

<?php
echo '<a HREF="javascript:RefAutoSet('PHP_FUNC','ftp://user:');", rawurlencode('foo @+%/'),
    
'@ftp.example.com/x.txt">';
?>

혹은, URL의 PATH_INFO 안에 경로 정보를 전달하고자 한다면:

예 2. rawurlencode() 예제 2

<?php
echo '<a HREF="javascript:RefAutoSet('PHP_FUNC','http://example.com/department_list_script/');",
  
rawurlencode('sales and marketing/Miami'), '">';
?>
295e

참고: rawurldecode(), urldecode(), urlencode(), RFC 1738.

Posted by 철냄비짱
,

urldecode

PHP 2008. 10. 30. 11:22

본 자료는 오토셋개발자그룹(www.autoset.org)에서 PHP 그룹(www.php.net)의 자료를 복사한 것으로 2006-12-01 10:16를 기준으로 작성되었습니다.

urldecode

(PHP 3, PHP 4 , PHP 5)

urldecode -- URL 인코드 문자열을 디코드합니다.

설명

string urldecode ( string str)

주어진 문자열의 %## 인코딩을 디코드합니다. 디코드한 문자열을 반환합니다.

예 1. urldecode() 예제

<?php
$a
= explode('&', $QUERY_STRING);
$i = 0;
while (
$i < count($a)) {
  
$b = split('=', $a[$i]);
   echo
'Value for parameter ', htmlspecialchars(urldecode($b[0])),
        
' is ', htmlspecialchars(urldecode($b[1])), "<br />\n";
  
$i++;
}
?>
3299

참고: urlencode(), rawurlencode(), rawurldecode().

Posted by 철냄비짱
,

foreach($_POST as $key => $value)
{
 if($value)
 {
  $value = strip_tags($value);
  ${$key} = RemoveXSS(trim($value));
 }
}


foreach($_GET as $key => $value)
{
 if($value)
 {
  $value = strip_tags($value);
  ${$key} = RemoveXSS(trim($value));
 }
}


구문 사용시 따로 변수를 받아내는 작업 필요 없이 바로 사용가능
Posted by 철냄비짱
,

int strtotime ( string $time [, int $now ] );

Examples

Example #1 A strtotime() example

<?php
echo strtotime("now"), "\n";
echo 
strtotime("10 September 2000"), "\n";
echo 
strtotime("+1 day"), "\n";
echo 
strtotime("+1 week"), "\n";
echo 
strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo 
strtotime("next Thursday"), "\n";
echo 
strtotime("last Monday"), "\n";
?>

Example #2 Checking for failure

<?php
$str 
'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp strtotime($str)) === false) {
    echo 
"The string ($str) is bogus";
} else {
    echo 
"$str == " date('l dS \o\f F Y h:i:s A'$timestamp);
}
?>
Posted by 철냄비짱
,

extract

PHP 2008. 10. 9. 14:11
 

extract

(PHP 3>= 3.0.7, PHP 4 , PHP 5)

extract --  배열의 현재 심볼 테이블로 변수들을 입력한다

설명

int extract ( array var_array [, int extract_type [, string prefix]])

이 함수는 배열의 값들을 현재 심볼 테이블에 입력하는데 사용된다. 연관 배열 var_array를 취해서 변수명을 키로, 변수값을 값으로 취급한다. extract_typeprefix 에 따라 각 키/값 쌍에 대해서 현재 심볼 테이블안에 변수를 생성한다.

참고: 버전 4.0.5에 시작하여, 이 함수는 추출된 변수의 수를 반환한다.

참고: EXTR_IF_EXISTSEXTR_PREFIX_IF_EXISTS는 버전 4.2.0에서부터 지원된다.

참고: EXTR_REFS 버전 4.3.0부터 지원된다.

extract()는 각 키가 유효한 변수명을 갖을수 있는지 검사 한다. 또한 심볼 테이블에 존재하는 변수들과의 충돌도 검사한다. 유효하지않은/숫자 키와 충돌인 경우를 취급하는 방법은 extract_type에 의해 결정된다. 다음 값들 중 하나가 될 수 있다:

EXTR_OVERWRITE

충돌이 발생하면, 기존 변수를 덮어쓴다.

EXTR_SKIP

충돌이 발생하면, 기존 변수를 덮어쓰지 않는다. variable.

EXTR_PREFIX_SAME

충돌이 발생하면, prefix를 변수명 앞에 첨가한다.

EXTR_PREFIX_ALL

prefix를 모든 변수명 앞에 첨가한다. PHP 4.0.5에서 시작하여, 이 플래그는 숫자 변수도 적용된다.

EXTR_PREFIX_INVALID

유효하지 않은/숫자 변수명 앞에만 prefix를 첨가한다. 이 플래그는 PHP 4.0.5에서 추가되었다.

EXTR_IF_EXISTS

현재 심볼 테이블에 이미 존재하는 변수만 덮어쓴다. 그렇지 않으면 아무것도 하지 않는다. 이 플래그는 유효한 변수 목록을 정의하고 이 변수들만 추출하는데 유용하다. 예를 들어, 이런 변수는 $_REQUEST에서 정의된 변수들이다. 이 플래그는 PHP 4.2.0에서 추가되었다.

EXTR_PREFIX_IF_EXISTS

현재 심볼 테이블에 앞첨가된 버전의 같은 변수가 존재할때만 앞첨가된 변수명을 생성한다. 이 플래그는 PHP 4.2.0에서 추가되었다.

EXTR_REFS

변수를 참조로써 추출한다. 입력된 변수 값이 var_array 매개변수의 값을 참조한다는 의미를 갖는다. 이 플래그는 그 자체로나 다른 플래그와 OR 연산하여 extract_type에서 사용할수 있다. 이 플래그는 PHP 4.3.0에서 추가되었다.

extract_type가 설정되지 않으면, EXTR_OVERWRITE가 설정되 있다고 가정한다.

prefixextract_typeEXTR_PREFIX_SAME, EXTR_PREFIX_ALL,EXTR_PREFIX_INVALID 또는, EXTR_PREFIX_IF_EXISTS 일때만 요구된다. 앞 첨가된 변수가 유효한 변수명이 아니면, 심볼테이블에 입력되지 않는다.

extract()는 심볼 테이블에 성공적으로 입력된 변수의 수를 반환한다.

extract()가 사용가능한 경우는 wddx_deserialize()에서 반환한 연관배열에 포함되어있는 심볼 테이블 변수들 안에 입력하는것이다.

예 1. extract() 예제코드

<?php

/* Suppose that $var_array is an array returned from
   wddx_deserialize */

$size = "large"
;
$var_array = array ("color" => "blue"
,
                  
"size"  => "medium"
,
                  
"shape" => "sphere"
);
extract ($var_array, EXTR_PREFIX_SAME, "wddx"
);

print
"$color, $size, $shape, $wddx_size\n"
;

?>

위 예제코드는 다음을 출력할것이다:

blue, large, sphere, medium

$size는 덮어씌어지지 않았다, 왜냐하면 EXTR_PREFIX_SAME를 설정했기 때문이다. 결과적으로 $wddx_size가 생성되었다. EXTR_SKIP가 설정되어 있으면, EXTR_OVERWRITE$size가 "medium" 값을 갖게 하고 EXTR_PREFIX_ALL는 새로운 변수인 $wddx_color, $wddx_size, $wddx_shape를 갖게한다.

연관 배열을 사용해야 한다. EXTR_PREFIX_ALLEXTR_PREFIX_INVALID를 사용하지 않으면 숫자로 인덱스된 배열은 결과를 도출할수 없다.

compact() 참고.



add a note add a note User Contributed Notes
extract
Csaba at alum dot mit dot edu
27-Nov-2005 07:41
Sometimes you may want to extract only a named subset of the key/value pairs in an array.  This keeps things more orderly and could prevent an unrelated variable from getting clobbered from an errant key.  For example,

$things = 'unsaid';
$REQUEST = array(He=>This, said=>1, my=>is, info=>2, had=>a,
                 very=>3, important=>test, things=>4);
$aVarToExtract = array(my, important, info);
extract (array_intersect_key ($REQUEST, array_flip($aVarToExtract)));

will extract
$my = 'is';
$important = 'test';
$info = 2;

but will leave certain
$things = 'unsaid'

Csaba Gabor from Vienna
NB.  Of course the composite request coming in from a web page is in $_REQUEST.
anon at anon dot org
30-May-2005 07:02
A warning about extract() and null values.

This might be an actual Zend2 Engine bug, but it's bad programming practice, so I'm sharing it here instead.

I often work in envrionments where E_STRICT (which would prevent errors like this) isn't on, and I don't have access to change it. I also use a very simple template class that in a nutshell works like this:

$t = new Template('somefile.php');
$t->title = $title;
$t->body = $body;
$t->display();

display() more or less looks like this:

function display(){
   extract(get_object_vars($this),EXTR_REFS);
   ob_start(); include $this->templateFileName;
   return ob_get_clean();
}

If any of the assigned values are null (let's say that in this case $title wasn't initialized above) it causes the engine to do all sorts of incredibly whacky stuff like certifiably lose track of variables in an incredibly inconsistent way. I traced the problem down to the fact that it's using the EXTR_REFS flag. I assume that in PHP's internal variable storage or reference counting mechanism, that trying to extract null references makes it lose track or count of something or rather.

In a nutshell, if you start getting wierd behavior when using extract() make sure that the array or object you are trying to get variables out of doesn't contain null keys or values!
kake26 at gmail dot com
01-May-2005 03:59
The following is a neat use for extract to store and manipulate large amounts of form data from. I basically loop through the $_POST and implode it seperating the key and value pairs by a space. Then store it in a db, the reversing function basically explodes the string to a array. Then converts the indexed array to a associative array then uses extract to seal the deal and make it easily available within a program. My main reason for sharing these are the fact I make some big web applications that store allot of forum data in a DB and these functions make it very easy to quickly and easily store and recall the data. I've contributed it because I spent many hours creating this code and recall going "I wish someone had previously submitted it to the page notes". Would have saved me allot of time and agony and I'm sure I'm not the only person that could really benefit from it, so I decided to share.

<?php
$stack
= array();
foreach (
$_POST as $key => $value
) {
array_push($stack, $key, $value
);
}
// store it
$block = implode(" ",$stack);
// yeilds a space delimited string
// insert query to store string in DB here, like the one below
$query = "INSERT INTO `sometable` VALUES('".$seluser."','".addslashes($block)."');"
;
$result = mysql_query($query) or die("Query failed for block insert: " . mysql_error
());
// note $seluser in my case is a user ID associated with that block
// in one of my web apps
?>

The nice thing is with the above we can quickly create a string of key and value pairs from the data the script-x got. Without really caring what their names are. You know how if register globals are on you say $someformvar rather than $_POST["someformvar"]; , basically the code below reads this previous created block returns it to that state. Sort of like presistant register globals.

<?php
// insert query to grab the previously stored string here
$query = "SELECT * FROM `sometable` WHERE `blockid` = '".addslashes($bid)."';"
;
$result = mysql_query($query) or die("Query failed read: " . mysql_error
());
$sql = mysql_fetch_array($result, MYSQL_ASSOC
);
$array = eplode(" ",$sql["data"
]);
for (
$i = 0; $i < sizeof($array); $i+=2
) {
$myassoc[$array[$i]] = isset($array[$i+1])?$array[$i+1]:NULL
;
}
extract($myassoc, EXTR_OVERWRITE
);
// now you're key and value pairs from $_POST have been restored
// instead of $_POST
?>
pg dot perfection at gmail dot com
14-Mar-2005 10:33
Here is a little example of how an extraction method should look like when it needs to work recursive (work on nested_arrays too)...

Note that this is only an example, it can be done more easily, and more advanced too.

<?php
/**
 * A nested version of the extract () function.
 *
 * @param    array    $array        The array which to extract the variables from
 * @param    int        $type        The type to use to overwrite (follows the same as extract () on PHP 5.0.3
 * @param    string    $prefix        The prefix to be used for a variable when necessary
 */
function extract_nested (&$array, $type = EXTR_OVERWRITE, $prefix = ''
)
{
  
/**
     *  Is the array really an array?
     */
  
if (!is_array ($array
))
   {
       return
trigger_error ('extract_nested (): First argument should be an array', E_USER_WARNING
);
   }

  
/**
     *  If the prefix is set, check if the prefix matches an acceptable regex pattern
     * (the one used for variables)
     */
  
if (!empty ($prefix) && !preg_match ('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $prefix
))
   {
       return
trigger_error ('extract_nested (): Third argument should start with a letter or an underscore', E_USER_WARNING
);
   }

  
/**
     * Check if a prefix is necessary. If so and it is empty return an error.
     */
  
if (($type == EXTR_PREFIX_SAME || $type == EXTR_PREFIX_ALL || $type == EXTR_PREFIX_IF_EXISTS) && empty ($prefix
))
   {
       return
trigger_error ('extract_nested (): Prefix expected to be specified', E_USER_WARNING
);
   }

  
/**
     * Make sure the prefix is oke
     */
  
$prefix = $prefix . '_'
;

  
/**
     *  Loop thru the array
     */
  
foreach ($array as $key => $val
)
   {
      
/**
         *  If the key isn't an array extract it as we need to do
         */
      
if (!is_array ($array[$key
]))
       {
           switch (
$type
)
           {
               default:
               case
EXTR_OVERWRITE
:
                  
$GLOBALS[$key] = $val
;
               break;
               case
EXTR_SKIP
:
                  
$GLOBALS[$key] = isset ($GLOBALS[$key]) ? $GLOBALS[$key] : $val
;
               break;
               case
EXTR_PREFIX_SAME
:
                   if (isset (
$GLOBALS[$key
]))
                   {
                      
$GLOBALS[$prefix . $key] = $val
;
                   }
                   else
                   {
                      
$GLOBALS[$key] = $val
;
                   }
               break;
               case
EXTR_PREFIX_ALL
:
                  
$GLOBALS[$prefix . $key] = $val
;
               break;
               case
EXTR_PREFIX_INVALID
:
                   if (!
preg_match ('#^[a-zA-Z_\x7f-\xff]$#', $key{0
}))
                   {
                      
$GLOBALS[$prefix . $key] = $val
;
                   }
                   else
                   {
                      
$GLOBALS[$key] = $val
;
                   }
               break;
               case
EXTR_IF_EXISTS
:
                   if (isset (
$GLOBALS[$key
]))
                   {
                      
$GLOBALS[$key] = $val
;
                   }
               break;
               case
EXTR_PREFIX_IF_EXISTS
:
                   if (isset (
$GLOBALS[$key
]))
                   {
                      
$GLOBALS[$prefix . $key] = $val
;
                   }
               break;
               case
EXTR_REFS
:
                  
$GLOBALS[$key] =& $array[$key
];
               break;
           }
       }
      
/**
         *  The key is an array... use the function on that index
         */
      
else
       {
          
extract_nested ($array[$key], $type, $prefix
);
       }
   }
}
?>
Michael Newton
03-Mar-2005 01:23
They say "If the result is not a valid variable name, it is not imported into the symbol table."

What they should say is that if _any_ of the results have invalid names, _none_ of the variables get extracted.

Under 4.3.10 on Windows 2000, I was pulling some mySQL records, but needed to convert two fields into IP addresses:
<?
extract
(mysql_fetch_assoc(mysql_query('SELECT * FROM foo'
)));
extract(mysql_fetch_assoc(mysql_query('SELECT INET_NTOA(bar) AS bar, INET_NTOA(baz) FROM foo'
)));
?>

I had forgotten the second AS modifier in the SQL query.  Because it couldn't extract a variable called INET_NTOA(baz) into the symbol table, it didn't do either of them.

(BTW I don't normally stack functions up like that!  Just to make a short example!)
22-Feb-2005 03:31
To make this perfectly clear (hopefully), an underscore is always added when the string is prefixed.
extract(array("color" => "blue"),EXTR_PREFIX_ALL,'');// note: prefix is empty
is the same as
$color='_blue';
Aaron Stone
17-Nov-2004 06:44
If you are working porting an older application, and taking the advice above, extracting only _SERVER, _SESSING, _COOKIE, _POST, _GET, you have forgotten to extract _FILES. Putting _FILES last and using EXTR_SKIP doesn't work because the name of the file upload box is already set as a variable containing only the temporary name of the uploaded file from one of the earlier extracts (I haven't tested to see which one specifically, however). A workaround is to put _FILES last and use EXTR_OVERWRITE. This allows extract to replace that temp-name-only variable with the full array of file upload information.
Adam Monsen <adamm at wazamatta dot com>
03-Oct-2004 12:03
As shown in the example, if your 'prefix' is used, a single underscore is added to the name of the extracted variable. Meaning, a prefix of 'p' becomes a prefix of 'p_', so 'blarg' prefixed would be 'p_blarg'.

If you're not sure what variables you've created through extraction, you can call get_defined_vars() to see all defined variables in the current scope.

Posted by 철냄비짱
,

PHP XML 파일 Pasrsing

PHP 2008. 10. 1. 11:41

// 파일명 getXML.php


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<meta name="robots" content="noindex, nofollow">
</head>
<?
session_start();
error_reporting(E_ALL^ E_NOTICE); # report all errors
ini_set("display_errors", "1"); # but do not echo the errors "0" or "1")


include_once "../../common/config/common.php";
include_once "../../common/inc/db_con.inc.php";
include_once "../../common/inc/function.inc.php";

$sdate = RemoveXSS($_REQUEST["sdate"]);
$umode = RemoveXSS($_REQUEST["umode"]);

class RSSParser {

 var $feed_info = array();
 var $feed_articles = array();
 var $inchannel = FALSE;
 var $initem = FALSE;
 var $inimage = FALSE;
 var $current_item = array();
 var $current_el = FALSE;

 // 여는 태그 처리
 function startElement($parser, $name, $attrs)
 {
  $el = strtoupper($name);
  if ($el == 'RSS') {
   return;
  } else if ($el == 'CHANNEL') {
   $this->inchannel = TRUE;
  } else if ($el == 'ITEM') {
   $this->initem = TRUE;
  } else {
   $this->current_el = $el;
  }
 }

 // 닫는 태그 처리
 function endElement($parser, $name)
 {
  $el = strtoupper($name);

  //아래 'CHANNEL', 'ITEM' 부분에서 제공해주는 사이트의 XML 부분에 따라 필드셋을 변경해준다.
  if ($el == 'RSS') {
   return;
  } else if ($el == 'CHANNEL') {
   $this->inchannel = FALSE;
  } else if ($el == 'ITEM') {
   $this->feed_articles[] = $this->current_item;
   $this->current_item = array();
   $this->initem = FALSE;
  } else {
   $this->current_el = FALSE;
  }
 }

 // 태그 사이의 데이터 처리
 function characterData($parser, $data)
 {
  if ($this->initem) {
   if ($this->current_el) {
    $this->current_item[$this->current_el] .= $data;
   }
  } else if ($this->inimage) {
  } else if ($this->inchannel) {
   if ($this->current_el) {
    $this->feed_info[$this->current_el] .= $data;
   }
  }
 }
}

function parse_save_rss($document)
{
 global $cu_conn;

 // RSS 피드의 인코딩을 UTF-8에 맞춤
 if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m', $document, $m)) {
  $in_enc = strtoupper($m[1]);
  if ($in_enc != 'UTF-8') {
   $document = preg_replace('/(<?xml.*encoding=[\'"])(.*?)([\'"].*?>)/m', '$1EUC-KR$3', $document);
   $document = iconv($in_enc, 'EUC-KR', $document);
  }
 }
 
 /*
 $document = str_replace("&lt;", "<", $document);
 $document = str_replace("&gt;", ">", $document);
 */

 // XML 및 RSS 분석기 생성
 $xml_parser = xml_parser_create('ISO-8859-1');
 $rss_parser = new RSSParser();

 xml_set_object($xml_parser, $rss_parser);
 xml_set_element_handler($xml_parser, "startElement", "endElement");
 xml_set_character_data_handler($xml_parser, "characterData");

 if (!xml_parse($xml_parser, $document, true)) {
  printf("XML error: %s at line %d \n", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser));
 } else {
  foreach ($rss_parser->feed_articles as $article) {

   /*
   echo $article["LINK"]."<br />";
   echo $article["TITLE"]."<br />";
   echo $article["DESCRIPTION"]."<br />";
   echo $article["PUBDATE"]."<br /><br /><br />";
   */

   $title = addslashes($article["TITLE"]);
   $description = $article["DESCRIPTION"];
   //$description = addslashes($article["DESCRIPTION"]);
   $link = addslashes($article["LINK"]);
   $pub_date = $article["PUBDATE"];

   if($modify_date == "") $modify_date = $register_date;
   
   $query = "SELECT NVL(MAX(UNO), 0) + 1 AS NEW_UNO, NVL(MAX(GNO), 0) + 1 AS NEW_GNO FROM TBWB_BOARD_P06 " ;
   $req = cubrid_execute($cu_conn, $query);
   $rows = cubrid_fetch($req);

   $new_uno = $rows["NEW_UNO"];
   $new_gno = $rows["NEW_GNO"];
   $new_reply_depth = "A";

   // Insert Or Update
   $query  = " INSERT INTO TBWB_BOARD_P06 ";
   $query .= " (UNO, GNO, REPLY_DEPTH, MEMB_ID, NICKNAME, SUBJECT, CONTENT, HTMLTAG_YN, ACCESS_IP, PUB_DATE, INS_DATE, UPD_DATE, UPLOAD_MULTIMEDIA_TYPE, RECOMMEND_YN, SUMMARY, FLV_URL, CATE_CODE, SUB_TITLE)";
   $query .= " VALUES";
   $query .= " ($new_uno, $new_gno, '$new_reply_depth', '".$_SESSION['SS_ADMIN_ID']."', '".$_SESSION['SS_ADMIN_NICKNAME']."', '$title', '$description', 'Y', '127.0.0.1', 'TO_TIMESTAMP('$pub_date','YYYY.MM.DD HH24:MI')', sys_timestamp, sys_timestamp, '$upload_multimedia_type', 'N', '$summary', '$flv_url', '$cate_code', '$sub_title') ";
   echo $query."<br /><br /><br />";

   //$req = cubrid_execute($cu_conn, $query);
   //exit;
   //@cubrid_close_request($req);
  }
 }

 xml_parser_free($xml_parser);
}

// 읽어올 피드 목록
//local 서버에 존재하는 xml 파일로 바로 파싱할때
$feed_urls = array('./dataXML.xml'); //80포트 일 경우 해당 URL을 바로 입력시 웹XML 파일 파싱 가능

foreach ($feed_urls as $url) {

 $handle = fopen($url, 'r');
 if ($handle) {
  $document = '';
  while (!feof($handle)) {
   $document .= fgets($handle, 4096);
  }

  //echo $document;
  //echo "url : ".$url."\n";
  // 읽어온 피드를 분석하여 DB에 저장
  parse_save_rss($document);

  fclose($handle);
 }
}


/* FTP 상의 XML 파일을 파싱할때
// define some variables
$server_file = '';
$local_file = '';

// set up basic connection
$conn_id = ftp_connect("");

// login with username and password
$login_result = ftp_login($conn_id, "tantanloan", "*qlalft");

// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

// close the connection
ftp_close($conn_id);
*/

?>

Posted by 철냄비짱
,
php 는 flush() 를 하기전까지는 아무것도 출력하지 않습니다.
그래서 최종 결과물의 헤더에는 Content-Length 가 있죠.

flush() 를 하는 순간 chunked 헤더를 날리고,
현재까지 버퍼의 내용을 출력합니다.
Content-Length 대신 chunk 데이터 앞에 chunk 크기가 주어집니다.

그러면 브라우저가 그것을 받아서 화면에 뿌려주죠.
페이지가 완성되지 않아도 화면을 구성할 수 있게되는 것입니다.

문제는 익스플로러가 이런 chunk 되지 않은
plain text 로 넘어오는 정보마저 받다말고 렌더링을 하려 하는것 같다는 것입니다.

해외에서의 접속을 좀 빨리 해볼 생각으로 페이지 압축전송을 했다가 우연히 발견하게 되었습니다.

다중중첩테이블 등에 의해 렌더링에 자원소모가 상당히 심한 페이지었는데,
압축전송을 한것 만으로 익스플로러에서는 눈에 띄게 렌더링이 빨라졌습니다.
(불여우에서는 원래 빨랐습니다. 그래도 약간의 향상은 있더군요.)

해외에서의 접속에도 생각 이상의 효과를 봤습니다.
전송속도를 체크해 보려고 수십메가의 파일을 다운로드해 봐도,
국내에서 다운받는것과 비슷한 속도가 났는데,
유독 php 페이지만 느리게 출력됐었습니다.
단지 압축전송을 한것만으로 그렇게 빨라지는것이 이해되지는 않지만,
결과가 좋아 만족합니다.
(서버는 한국, 대상은 일본이고,
한일간의 주요 네트워크 장비중 한->일 방향에서,
텍스트 필터링을 하는 뭔가가 있지 않나 생각해봅니다.)


결론은 압축전송 입니다.
php 에서 간단히 구현할 수 있는것이
ob_gzhandler 입니다.
zlib 를 설치하면 사용할 수 있습니다.

ob_start('ob_gzhandler');
하면,
출력되는 모든 정보가 압축이 되고,
브라우저가 이를 풀어서 보여줍니다.

이렇게 하면 압축이 되었으므로,
모두 받아서 풀기전까지는 브라우저가 내용을 보여줄 수 없습니다.

이것의 단점은 flush() 의 불가 라는 점입니다.
ob_flush() 는 무시되고,
flush() 를 하면 chunked 헤더를 날리지만,
결국에는 하나로 압축되어 한덩어리의 chunk 데이터만 보내집니다.

해외에서의 접속에서 flush() 가 필요하다면,
압축전송을 포기하거나,
직접 작성할 수 밖에 없습니다.

ob_handler 와 ob_flush 를 직접 작성하면,
flush() 와 연동해서 충분히 제작 가능합니다.

템플릿을 사용한다면 flush() 를 위해
ob_start 를 안하고 있다가,
템플릿 출력시에 동작하게 하면 간단히 적용하기에 좋을것입니다.


출처 : http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=53266&sca=%BA%EA%B6%F3%BF%EC%C0%FA
Posted by 철냄비짱
,

// 한글을 적당히 잘라주는 함수
function CutString($str_total, $str_cut_len)
{  // cust_string(전체문자열, 보여줄 문자수:byte)

 $str_total_len = strlen($str_total);   // 전체 문자수 : byte
 $str_view_len = $str_cut_len;     // 보여줄 문자수 : byte

 for($k=0; $k < $str_view_len - 1; $k++ )
 {
  if ( ord(substr($str_total, $k, 1)) > 127 ) // substr() : byte
  { 
   $k++;    // 한글은 2바이트이기에
  }
 }//for($k=0; $k < $str_view_len - 1; $k++ )

 if($str_total_len > $str_view_len)
 {
  $str_view = substr($str_total, 0, $k) . '..';
 }
 else
 {
  $str_view = $str_total;
 }//if($str_total_len > $str_view_len)

 return $str_view;
}//function CutString($str_total, $str_cut_len)


사용법은 간단....
$subject = CutString($row[title], 30);

수 많은 문자열 커팅함수 중에 하나...
특별히 잘난 것도, 못난 것도 없는 무난한 함수

Posted by 철냄비짱
,
<?php
 
if(!empty($_FILES["magfile"]))
  {
   
$uploaddir = $_SERVER['DOCUMENT_ROOT']."/dainsider/magazines/";
   
$uploaddir.="magazine.pdf";
   
   
//Copy the file to some permanent location
   
if(move_uploaded_file($_FILES["magfile"]["tmp_name"], $uploaddir))
    {
      echo
"Magazine Updated!";
    }
    else
    {
      echo
"There was a problem when uploding the new file, please contact ".$admin_email." about this.";
     
print_r($_FILES);
    }
  }
?>

위에서 처럼 DOCUMENT_ROOT 를 사용하여 절대경로로 사용.
뭣보다 TRUE, FALSE 를 반환해주고 파일 카피가 아닌 move 기능

업로드 함수를 사용할때 유용
Posted by 철냄비짱
,