PHP安全フィルタリングと常用関数のまとめ

198900 ワード

1.セキュリティフィルタクラス-汎用データフィルタ
/**
*      -      
*  Controller     :$this->controller->fliter_escape($value)
* @param string $value        
* @return string|array
*/
function fliter_escape($value) {
if (is_array($value)) {
  foreach ($value as $k => $v) {
   $value[$k] = self::fliter_str($v);
  }
} else {
  $value = self::fliter_str($value);
}
return $value;
}


2.セキュリティフィルタクラス-javascript,css,iframes,objectなどの非セキュリティパラメータをフィルタする

/**
*      -  javascript,css,iframes,object            
*  Controller     :$this->controller->fliter_script($value)
* @param  string $value       
* @return string
*/
function fliter_script($value) {
$value = preg_replace("/(javascript:)?on(click|load|key|mouse|error|abort|move|unload|change|dblclick|move|reset|resize|submit)/i","&111n\\2",$value);
$value = preg_replace("/(.*?)/si","",$value);
$value = preg_replace("/(.*?)/si","",$value);
$value = preg_replace ("//iesU", '', $value);
return $value;
}


3.セキュリティ・フィルタ・クラス-HTMLタグのフィルタ
PHPが提供するhtmlentities関数を使用してHTMLをフィルタリングします.この関数は、すべてのHTMLタグ文字(&、など)を対応するHTMLエンティティに変換し、アプリケーション・ストレージ・レイヤが取り出した後に安全にレンダリングできるようにします.しかし、画像やリンクなどのHTML要素を入力できる場合があります.
 :            ,           。
/**
*      -  HTML  
*  Controller     :$this->controller->fliter_html($value)
* @param  string $value       
* @return string
*/
function fliter_html($value) {
if (function_exists('htmlspecialchars')) return htmlspecialchars($value);
return str_replace(array("&", '"', "'", ", ">"), array("&", "\"", "'", ", ">"), $value);
}




/**
*      -  HTML  
*  Controller     :$this->controller->fliter_html($value)
* @param  string $value       
* @return string
*/
function fliter_html($value) {
if (function_exists('htmlspecialchars')) return htmlspecialchars($value);
return str_replace(array("&", '"', "'", ", ">"), array("&", "\"", "'", ", ">"), $value);
}


4.安全フィルタ類-文字列フィルタ特殊危害文字
/**
*      -               
*  Controller     :$this->controller->fliter_str($value)
* @param  string $value       
* @return string
*/
function fliter_str($value) {
$badstr = array("\0", "%00", "\r", '&', ' ', '"', "'", ", ">", "   ", "%3C", "%3E");
$newstr = array('', '', '', '&', ' ', '"', ''', "<", ">", "   ", "<", ">");
$value  = str_replace($badstr, $newstr, $value);
$value  = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $value);
return $value;
}


5.私有道路力の安全転化
/**
*         
*  Controller     :$this->controller->filter_dir($fileName)
* @param string $fileName
* @return string
*/
function filter_dir($fileName) {
$tmpname = strtolower($fileName);
$temp = array(':/',"\0", "..");
if (str_replace($temp, '', $tmpname) !== $tmpname) {
  return false;
}
return $fileName;
}

6.ディレクトリのフィルタ
/**
*     
*  Controller     :$this->controller->filter_path($path)
* @param string $path
* @return array
*/
public function filter_path($path) {
$path = str_replace(array("'",'#','=','`','$','%','&',';'), '', $path);
return rtrim(preg_replace('/(\/){2,}|(\\\){1,}/', '/', $path), '/');
}

7.PHPラベルのフィルタ
/**
*   PHP  
*  Controller     :$this->controller->filter_phptag($string)
* @param string $string
* @return string
*/
public function filter_phptag($string) {
return str_replace(array(''), array('', '?>'), $string);
}



8.セキュリティ・フィルタ・クラス-戻り関数

/**
*      -    
*  Controller     :$this->controller->str_out($value)
* @param  string $value       
* @return string
*/
public function str_out($value) {
$badstr = array(", ">", "%3C", "%3E");
$newstr = array(", ">", ", ">");
$value  = str_replace($newstr, $badstr, $value);
return stripslashes($value); //   
}


9.phpファイルのアップロードタイプを判断し、不安全なデータをフィルタリングする方法
/*
php                   
*/
function s_addslashes($string, $force = 0) { 
 if(!get_magic_quotes_gpc()) { 
  if(is_array($string)) { 
   foreach($string as $key => $val) { 
    $string[$key] = s_addslashes($val, $force); 
   } 
  } else { 
   $string=str_replace("","& # x",$string); // 
 
//          
   $string = addslashes($string); 
  } 
 } 
 return $string; 
} 
//    : 
$_COOKIE = c_addslashes($_COOKIE); 
$_POST   = c_addslashes($_POST); 
$_GET   = c_addslashes($_GET); 
 
//         
if($_FILES){  
 foreach( $_FILES as $key => $_value ) 
 { 
  $_FILES[$key]['type'] =$_value['type'];   
 } 
 if(substr($_FILES[$key]['type'],0,6) !='image/') 
 { 
  exit; 
 } 
}

10.xssフィルタ関数
/**
 * xss    
 *
 * @param $string
 * @return string
 */
function remove_xss($string) {
 $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S|', '', $string);
 $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
 $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 
 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 
 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 
 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 
 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 
 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 
 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 
 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 
 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 
 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 
 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 
 'onunload');
 $parm = array_merge($parm1, $parm2);
 for ($i = 0; $i < sizeof($parm); $i++) {
  $pattern = '/';
  for ($j = 0; $j < strlen($parm[$i]); $j++) {
   if ($j > 0) {
    $pattern .= '(';
    $pattern .= '([x|X]0([9][a][b]);?)?';
    $pattern .= '|(�([9][10][13]);?)?';
    $pattern .= ')?';
   }
   $pattern .= $parm[$i][$j];
  }
  $pattern .= '/i';
  $string = preg_replace($pattern, ' ', $string);
 }
 return $string;
}



11.ASCIIコードを0-28からフィルタする制御文字
/**
 *   
 *   ASCII  0-28     
 * @return String
 */
function trim_unsafe_control_chars($str) {
 $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
 return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
}

echo trim_unsafe_control_chars(" asdasdas");
echo "
"
;

12.テキストフィールドの内容のフォーマット
/**
 *         
 *
 * @param $string      
 * @return string
 */
function trim_textarea($string) {
 $string = nl2br ( str_replace ( ' ', ' ', $string ) );
 return $string;
}
echo trim_textarea("asc sda  sdas");
echo "
"
;

13.js出力に適した文字列にテキストをフォーマットする
/**
 *         js      
 * @param string $string         
 * @param intval $isjs           ,     
 * @return string        
 */
function format_js($string, $isjs = 1) {
 $string = addslashes(str_replace(array("\r", "
"
, "\t"), array('', '', ''), $string)); return $isjs ? 'document.write("'.$string.'");' : $string; } echo format_js("asc sda sdas"); echo "
"
;

14.現在のページの完全なURLアドレスを取得する
/**
 *   
 *         URL  
 */
function get_url() {
 $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
 $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
 $path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
 $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
 return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}


echo get_url();

echo "
"
;

15.取得要求ip
/**
 *   
 *     ip
 *
 * @return ip  
 */
function ip() {
 if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  $ip = getenv('HTTP_CLIENT_IP');
 } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  $ip = getenv('HTTP_X_FORWARDED_FOR');
 } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  $ip = getenv('REMOTE_ADDR');
 } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  $ip = $_SERVER['REMOTE_ADDR'];
 }
 return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}
function get_cost_time() {
 $microtime = microtime ( TRUE );
 return $microtime - SYS_START_TIME;
}


echo ip();
echo "
"
;

16.テンプレート呼び出し
/**
 *     
 *
 * @param $module
 * @param $template
 * @param $istag
 * @return unknown_type
 */
function template($module = 'content', $template = 'index', $style = '') {
 if(strpos($module, 'plugin/')!== false) {
  $plugin = str_replace('plugin/', '', $module);
  return p_template($plugin, $template,$style);
 }
 $module = str_replace('/', DIRECTORY_SEPARATOR, $module);
 if(!empty($style) && preg_match('/([a-z0-9\-_]+)/is',$style)) {
 } elseif (empty($style) && !defined('STYLE')) {
  if(defined('SITEID')) {
   $siteid = SITEID;
  } else {
   $siteid = param::get_cookie('siteid');
  }
  if (!$siteid) $siteid = 1;
  $sitelist = getcache('sitelist','commons');
  if(!empty($siteid)) {
   $style = $sitelist[$siteid]['default_style'];
  }
 } elseif (empty($style) && defined('STYLE')) {
  $style = STYLE;
 } else {
  $style = 'default';
 }
 if(!$style) $style = 'default';
 $template_cache = app_base::load_sys_class('template_cache');
 $compiledtplfile = ROOT_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
 if(file_exists(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
  if(!file_exists($compiledtplfile) || (@filemtime(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) {
   $template_cache->template_compile($module, $template, $style);
  }
 } else {
  $compiledtplfile = ROOT_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
  if(!file_exists($compiledtplfile) || (file_exists(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) {
   $template_cache->template_compile($module, $template, 'default');
  } elseif (!file_exists(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
   showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
  }
 }
 return $compiledtplfile;
}

17.変換バイト数が他の単位
/**
 *   
*           
*
*
* @param string $filesize     
* @return string     
*/
function sizecount($filesize) {
 if ($filesize >= 1073741824) {
  $filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
 } elseif ($filesize >= 1048576) {
  $filesize = round($filesize / 1048576 * 100) / 100 .' MB';
 } elseif($filesize >= 1024) {
  $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
 } else {
  $filesize = $filesize.' Bytes';
 }
 return $filesize;
}

echo sizecount(35632454);
echo "
"
;

18.文字列暗号化、復号化関数
/**
 *   
*      、    
*
*
* @param string $txt     
* @param string $operation ENCODE   ,DECODE   ,    ,   ENCODE,
* @param string $key    :  、  、   
* @param string $expiry      
* @return string
*/
function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
 	$key_length = 4;
 	$key = md5($key != '' ? $key : app_base::load_config('system', 'auth_key'));
 	$fixedkey = md5($key);
 	$egiskeys = md5(substr($fixedkey, 16, 16));
 	$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
 	$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
 	$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
 	$i = 0; $result = '';
 	$string_length = strlen($string);
 	for ($i = 0; $i < $string_length; $i++){
  		$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
 	}
 	if($operation == 'ENCODE') {
  		return $runtokey . str_replace('=', '', base64_encode($result));
 	} 
 	else {
  		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
   			return substr($result, 26);
  		} 
  		else 
  		{
   			return '';
  		}
 	}
}

$a1 = sys_auth("liman123456789aaaaa   //dsas",'ENCODE','manasdas123',1);
echo $a1."
"
; $a2 = sys_auth($a1,'DECODE','manasdas123',1); echo $a2."
"
;

19.クエリ文字が文字列に存在するかどうか
/**
 *              
 *
 * @param $haystack    
 * @param $needle       
 * @return bool
 */
function str_exists($haystack, $needle)
{
 return !(strpos($haystack, $needle) === FALSE);
}

echo str_exists('liman','c');
echo "
"
;

20.ファイル拡張の取得
/**
 *  
 * 
 *       
 *
 * @param $filename    
 * @return    
 */
function fileext($filename) {
 return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

echo fileext('liman.c');
echo "
"
;

21.テンプレートラベルキャッシュのロード
/**
 *         
 * @param string $name    
 * @param integer $times     
 */
function tpl_cache($name,$times = 0) {
 $filepath = 'tpl_data';
 $info = getcacheinfo($name, $filepath);
 if (SYS_TIME - $info['filemtime'] >= $times) {
  return false;
 } else {
  return getcache($name,$filepath);
 }
}



22.ライトキャッシュ、デフォルトはファイルキャッシュ、キャッシュ構成はロードされません.
/**
 *     ,       ,       。
 * @param $name     
 * @param $data     
 * @param $filepath     (    ) caches/cache_$filepath/
 * @param $type     [file,memcache,apc]
 * @param $config     
 * @param $timeout     
 */
function setcache($name, $data, $filepath='', $type='file', $c ='AND ', $in_column = false) {
 if($in_column && is_array($data)) {
  $ids = '\''.implode('\',\'', $data).'\'';
  $sql = "$in_column IN ($ids)";
  return $sql;
 } else {
  if ($front == '') {
   $front = ' AND ';
  }
  if(is_array($data) && count($data) > 0) {
   $sql = '';
   foreach ($data as $key => $val) {
    $sql .= $sql ? " $front $key = '$val' " : " $key = '$val' ";
   }
   return $sql;
  } else {
   return $data;
  }
 }
}



23.email形式が正しいかどうかを判断する
/**
 *   email      
 * @param $email
 */
function is_email($email) {
 return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

24.iconv編集変換
/**
 * iconv     
 */
if (!function_exists('iconv')) {
 function iconv($in_charset, $out_charset, $str) {
  $in_charset = strtoupper($in_charset);
  $out_charset = strtoupper($out_charset);
  if (function_exists('mb_convert_encoding')) {
   return mb_convert_encoding($str, $out_charset, $in_charset);
  } else {
   app_base::load_sys_func('iconv');
   $in_charset = strtoupper($in_charset);
   $out_charset = strtoupper($out_charset);
   if ($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312')) {
    return utf8_to_gbk($str);
   }
   if (($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8') {
    return gbk_to_utf8($str);
   }
   return $str;
  }
 }
}

25.idによる表示連動メニューの取得
/**
 *   id        
 * @param $linkageid     ID
 * @param $keyid   keyid
 * @param $space      
 * @param $tyoe 1        ,       3         ,2          ,4     ID
 * @param $result       1
 * @param $infos       2
 */
function get_linkage($linkageid, $keyid, $space = '>', $type = 1, $result = array(), $infos = array()) {
 if($space=='' || !isset($space))$space = '>';
 if(!$infos) {
  $datas = getcache($keyid,'linkage');
  $infos = $datas['data'];
 }
 if($type == 1 || $type == 3 || $type == 4) {
  if(array_key_exists($linkageid,$infos)) {
   $result[]= ($type == 1) ? $infos[$linkageid]['name'] : (($type == 4) ? $linkageid :$infos[$linkageid]);
   return get_linkage($infos[$linkageid]['parentid'], $keyid, $space, $type, $result, $infos);
  } else {
   if(count($result)>0) {
    krsort($result);
    if($type == 1 || $type == 4) $result = implode($space,$result);
    return $result;
   } else {
    return $result;
   }
  }
 } else {
  return $infos[$linkageid]['name'];
 }
}

26.IEブラウザの判断
/**
 * IE     
 */
function is_ie() {
 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
 if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) echo "no IE";
 if(strpos($useragent, 'msie ') !== false) echo "yes IE";
}

is_ie();
echo "
"
;

27.ファイルのダウンロード
/**
 *     
 * @param $filepath     
 * @param $filename     
 */
function file_down($filepath, $filename = '') {
 if(!$filename) $filename = basename($filepath);
 if(is_ie()) $filename = rawurlencode($filename);
 $filetype = fileext($filename);
 $filesize = sprintf("%u", filesize($filepath));
 if(ob_get_length() !== false) @ob_end_clean();
 header('Pragma: public');
 header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
 header('Cache-Control: no-store, no-cache, must-revalidate');
 header('Cache-Control: pre-check=0, post-check=0, max-age=0');
 header('Content-Transfer-Encoding: binary');
 header('Content-Encoding: none');
 header('Content-type: '.$filetype);
 header('Content-Disposition: attachment; filename="'.$filename.'"');
 header('Content-length: '.$filesize);
 readfile($filepath);
 exit;
}


28.文字列がutf 8符号化であるか否かを判断し、英語と半角文字はtureを返す

/**
 *         utf8  ,         ture
 * @param $string
 * @return bool
 */
function is_utf8($string) {
 return preg_match('%^(?:
     [\x09\x0A\x0D\x20-\x7E] # ASCII
     | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
     | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
     | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
     | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
     | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
     | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
     | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
     )*$%xs', $string);
}


29.組立生成ID番号
/**
 *     ID 
 * @param $modules    
 * @param $contentid   ID
 * @param $siteid   ID
 */
function id_encode($modules,$contentid, $siteid) {
 return urlencode($modules.'-'.$contentid.'-'.$siteid);
}
/**
 *   ID
 * @param $id   ID
 */
function id_decode($id) {
 return explode('-', $id);
}

$id_a1 = id_encode('A','aaa','1');
echo $id_a1;
echo "
"
; print_r(id_decode($id_a1)); echo "
"
;

30.ユーザーのパスワードを暗号化する

/**
 *           
 * @param $password
 * @param $encrypt //     ,         
 * @return array/password
 */
function password($password, $encrypt='') {
 $pwd = array();
 $pwd['encrypt'] = $encrypt ? $encrypt : create_randomstr();
 $pwd['password'] = md5(md5(trim($password)).$pwd['encrypt']);
 return $encrypt ? $pwd['password'] : $pwd;
}

echo password('lm123456','lm');
echo "
"
;

31.入力にエラー文字が含まれているかどうかを検出する

 /**
 *              
 *
 * @param char $string          
 * @return TRUE or FALSE
 */
function is_badword($string) {
 $badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","
"
,"#"); foreach($badwords as $value){ if(strpos($string, $value) !== FALSE) { return TRUE; } } return FALSE; }

32.データの符号化変換
/**
 *          
 * @param array/string $data    
 * @param string $input         
 * @param string $output       
 */
function array_iconv($data, $input = 'gbk', $output = 'utf-8') {
 if (!is_array($data)) {
  return iconv($input, $output, $data);
 } else {
  foreach ($data as $key=>$val) {
   if(is_array($val)) {
    $data[$key] = array_iconv($val, $input, $output);
   } else {
    $data[$key] = iconv($input, $output, $val);
   }
  }
  return $data;
 }
}

33.サムネイル関数の生成
/**
 *        
 * @param $imgurl     
 * @param $width      
 * @param $height      
 * @param $autocut            ,            0 ,    
 * @param $smallpic           
 */
function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif') {
 global $image;
 $upload_url = app_base::load_config('system','upload_url');
 $upload_path = app_base::load_config('system','upload_path');
 if(empty($imgurl)) return IMG_PATH.$smallpic;
 $imgurl_replace= str_replace($upload_url, '', $imgurl);
 if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;
 if(!file_exists($upload_path.$imgurl_replace)) return IMG_PATH.$smallpic;
 list($width_t, $height_t, $type, $attr) = getimagesize($upload_path.$imgurl_replace);
 if($width>=$width_t || $height>=$height_t) return $imgurl;
 $newimgurl = dirname($imgurl_replace).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl_replace);
 if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;
 if(!is_object($image)) {
  app_base::load_sys_class('image','','0');
  $image = new image(1,0);
 }
 return $image->thumb($upload_path.$imgurl_replace, $upload_path.$newimgurl, $width, $height, '', $autocut) ? $upload_url.$newimgurl : $imgurl;
}


34.ウォーターマークの追加
/**
 *     
 * @param $source      
 * @param $target         ,    ,    
 * @param $siteid   id,       id      
 */
function watermark($source, $target = '',$siteid) {
 global $image_w;
 if(empty($source)) return $source;
 if(!extension_loaded('gd') || strpos($source, '://')) return $source;
 if(!$target) $target = $source;
 if(!is_object($image_w)){
  app_base::load_sys_class('image','','0');
  $image_w = new image(0,$siteid);
 }
  $image_w->watermark($source, $target);
 return $target;
}

35.添付ファイルのアドレスを絶対アドレスに変換する

/**
 *             
 * @param $path     
 */
function atturl($path) {
 if(strpos($path, ':/')) {
  return $path;
 } else {
  $sitelist = getcache('sitelist','commons');
  $siteid = get_siteid();
  $siteurl = $sitelist[$siteid]['domain'];
  $domainlen = strlen($sitelist[$siteid]['domain'])-1;
  $path = $siteurl.$path;
  $path = substr_replace($path, '/', strpos($path, '//',$domainlen),2);
  return  $path;
 }
}

36.見出しスタイルの生成
/**
 *       
 * @param $style   
 * @param $html        STYLE
 */
function title_style($style, $html = 1) {
 $str = '';
 if ($html) $str = ' style="';
 $style_arr = explode(';',$style);
 if (!empty($style_arr[0])) $str .= 'color:'.$style_arr[0].';';
 if (!empty($style_arr[1])) $str .= 'font-weight:'.$style_arr[1].';';
 if ($html) $str .= '" ';
 return $str;
}

37.添付ファイルのアップロード検証の生成
/**
 *         
 * @param $args   
 * @param $operation     (    )
 */
function upload_key($args) {
 $pc_auth_key = md5(app_base::load_config('system','auth_key').$_SERVER['HTTP_USER_AGENT']);
 $authkey = md5($args.$pc_auth_key);
 return $authkey;
}

38.検証コードクラス
/*
     
 */
session_start(); 
Header("Content-type: image/gif"); 
class SecurityCode 
{ 
private $codes = ''; 
function __construct() 
{ 
$code = '0-1-2-3-4-5-6-7-8-9-A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z'; 
$codeArray = explode('-',$code); 
shuffle($codeArray); 
$this->codes = implode('',array_slice($codeArray,0,4)); 
} 
public function CreateImg() 
{ 
$_SESSION['check_pic'] = $this->codes; 
$img = imagecreate(70,25); 
imagecolorallocate($img,222,222,222); 
$testcolor1 = imagecolorallocate($img,255,0,0); 
$testcolor2 = imagecolorallocate($img,51,51,51); 
$testcolor3 = imagecolorallocate($img,0,0,255); 
$testcolor4 = imagecolorallocate($img,255,0,255); 
for ($i = 0; $i < 4; $i++) 
{ 
imagestring($img,rand(5,6),8 + $i * 15,rand(2,8),$this->codes[$i],rand(1,4)); 
} 
imagegif($img); 
} 
} 
$code = new SecurityCode(); 
$code->CreateImg(); 
$code = NULL; 



セキュリティポリシー
1、php      
(1)  php      
(2)    “   ”
(3)        。
2、       ,       “ ” 
2.1          ,   ,          。
2.2       point          
3、   
   3.1               
   3.2   mysql    
       (1)        
       (2)          ,     
       (3)       
(4)       
(5)           
(6)       
(7)union、join 
(8)    %、_
(9)            sql 
   33        
       2.3.1 php                。
       2.3.2        。
2.3.3     
    (1)        intval()  
    (2)          
(3)         。
(4)       addslashes、mysql_escape_string     。
4、  xss  
4.1Xss    
4.2  xss    
4.3 XSS  
5、CSRF
5.1    CSRF  
5.2    
6、   
7、  CC  


php      

php.ini   display_errors = OFF  
or
code:  error_reporting(0)

 php.ini  magic_quotes_gpc = OFF
   addslashes     

 php.ini  register_globals = OFF

    SQL              。 




  PHP     mysql_real_escape_string()               。                ,                   MySQL           。   7            。 

   
$sql = “select count(*) as ctr from users where username='”.$username.”' and password='”. $pw.”' limit 1″; 

  
$sql = “select count(*) as ctr from users where username='”.mysql_real_escape_string($username).”' and password='”. mysql_real_escape_string($pw).”' limit 1″; 


$Exec_Commond  = "( \\s|\\S)*(exec(\\s|\\+)+(s|x)p\\w+)(\\s|\\S)*";
$Simple_XSS = "( \\s|\\S)*((%3C)|)(\\s|\\S)*";
$Eval_XSS  = "( \\s|\\S)*((%65)|e)(\\s)*((%76)|v)(\\s)*((%61)|a)(\\s)*((%6C)|l)(\\s|\\S)*";
$Image_XSS  = "( \\s|\\S)*((%3C)|)(\\s|\\S)*" ;
$Script_XSS = "( \\s|\\S)*((%73)|s)(\\s)*((%63)|c)(\\s)*((%72)|r)(\\s)*((%69)|i)(\\s)*((%70)|p)(\\s)*((%74)|t)(\\s|\\S)*";
$SQL_Injection = "( \\s|\\S)*((%27)|(')|(%3D)|(=)|(/)|(%2F)|(\")|((%22)|(-|%2D){2})|(%23)|(%3B)|(;))+(\\s|\\S)*";