設為首頁收藏本站

 取回密碼
 註冊
搜尋
熱搜: Redump discuz
檢視: 22|回覆: 0

【分享】 PHP安全過濾與常用函數

[複製連結]
發表於 2024年4月2日 16:06:04 | 顯示全部內容 |閱讀模式
1. 安全過濾類-通用過濾

  1. /**
  2. * 安全過濾類-通用過濾
  3. *  Controller中使用方法:$this->controller->fliter_escape($value)
  4. * @param string $value 需要過濾的變量
  5. * @return string|array
  6. */
  7. function fliter_escape($value) {
  8. if (is_array($value)) {
  9.   foreach ($value as $k => $v) {
  10.    $value[$k] = self::fliter_str($v);
  11.   }
  12. } else {
  13.   $value = self::fliter_str($value);
  14. }
  15. return $value;
  16. }
複製程式碼


2. 安全過濾類-過濾javascript,css,iframes,object等不安全參數

  1. /**
  2. * 安全過濾類-過濾javascript,css,iframes,object等不安全參數 過濾級別高
  3. *  Controller中使用方法:$this->controller->fliter_script($value)
  4. * @param  string $value 需要過濾的值
  5. * @return string
  6. */
  7. function fliter_script($value) {
  8. $value = preg_replace("/(javascript:)?on(click|load|key|mouse|error|abort|move|unload|change|dblclick|move|reset|resize|submit)/i","&111n\\2",$value);
  9. $value = preg_replace("/(.*?)<\/script>/si","",$value);
  10. $value = preg_replace("/(.*?)<\/iframe>/si","",$value);
  11. $value = preg_replace ("//iesU", '', $value);
  12. return $value;
  13. }
複製程式碼


3. 安全過濾類-過濾HTML標籤
使用PHP提供的htmlentities函式過濾HTML,函式會將所有HTML標籤字元(&、<、>等)轉換為對應的HTML,以便在應用存儲層取出後安全渲染。但是有時候我們是允許輸入某些HTML元素的,尤其是輸入 rich text 的時候,比如圖片、連結。輸入既要驗證也要過濾,以確保其符合預期且安全。


  1. /**
  2. * 安全過濾類-過濾HTML標籤
  3. *  Controller中使用方法:$this->controller->fliter_html($value)
  4. * @param  string $value 需要過濾的值
  5. * @return string
  6. */
  7. function fliter_html($value) {
  8. if (function_exists('htmlspecialchars')) return htmlspecialchars($value);
  9. return str_replace(array("&", '"', "'", "<", ">"), array("&", """, "'", "<", ">"), $value);
  10. }




  11. /**
  12. * 安全過濾類-過濾HTML標籤
  13. *  Controller中使用方法:$this->controller->fliter_html($value)
  14. * @param  string $value 需要過濾的值
  15. * @return string
  16. */
  17. function fliter_html($value) {
  18. if (function_exists('htmlspecialchars')) return htmlspecialchars($value);
  19. return str_replace(array("&", '"', "'", "<", ">"), array("&", """, "'", "<", ">"), $value);
  20. }
複製程式碼


4.安全過濾類-字串過濾 過濾特殊有危害字元

  1. /**
  2. * 安全過濾類-字串過濾 過濾特殊有危害字元
  3. *  Controller中使用方法:$this->controller->fliter_str($value)
  4. * @param  string $value 需要過濾的值
  5. * @return string
  6. */
  7. function fliter_str($value) {
  8. $badstr = array("\0", "%00", "\r", '&', ' ', '"', "'", "<", ">", "   ", "%3C", "%3E");
  9. $newstr = array('', '', '', '&', ' ', '"', ''', "<", ">", "   ", "<", ">");
  10. $value  = str_replace($badstr, $newstr, $value);
  11. $value  = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $value);
  12. return $value;
  13. }
複製程式碼


5.路徑安全轉換

  1. /**
  2. * 路徑安全轉換
  3. *  Controller中使用方法:$this->controller->filter_dir($fileName)
  4. * @param string $fileName
  5. * @return string
  6. */
  7. function filter_dir($fileName) {
  8. $tmpname = strtolower($fileName);
  9. $temp = array(':/',"\0", "..");
  10. if (str_replace($temp, '', $tmpname) !== $tmpname) {
  11.   return false;
  12. }
  13. return $fileName;
  14. }
複製程式碼


6.目錄過濾

  1. /**
  2. * 目錄過濾
  3. *  Controller中使用方法:$this->controller->filter_path($path)
  4. * @param string $path
  5. * @return array
  6. */
  7. public function filter_path($path) {
  8. $path = str_replace(array("'",'#','=','`','$','%','&',';'), '', $path);
  9. return rtrim(preg_replace('/(\/){2,}|(\\\){1,}/', '/', $path), '/');
  10. }
複製程式碼


7.過濾PHP標籤

  1. /**
  2. * 過濾PHP標籤
  3. *  Controller中使用方法:$this->controller->filter_phptag($string)
  4. * @param string $string
  5. * @return string
  6. */
  7. public function filter_phptag($string) {
  8. return str_replace(array(''), array('<?', '?>'), $string);
  9. }
複製程式碼


8. 安全過濾類-返回函式

  1. /**
  2. * 安全過濾類-返回函式
  3. *  Controller中使用方法:$this->controller->str_out($value)
  4. * @param  string $value 需要過濾的值
  5. * @return string
  6. */
  7. public function str_out($value) {
  8. $badstr = array("<", ">", "%3C", "%3E");
  9. $newstr = array("<", ">", "<", ">");
  10. $value  = str_replace($newstr, $badstr, $value);
  11. return stripslashes($value); //底線
  12. }
複製程式碼


9.php判斷檔案上傳類型及過濾不安全資料的方法

  1. /*
  2. php判斷檔案上傳類型及過濾不安全資料的方法
  3. */
  4. function s_addslashes($string, $force = 0) {
  5. if(!get_magic_quotes_gpc()) {
  6.   if(is_array($string)) {
  7.    foreach($string as $key => $val) {
  8.     $string[$key] = s_addslashes($val, $force);
  9.    }
  10.   } else {
  11.    $string=str_replace("&#x","& # x",$string); //

  12. //過濾一些不安全字元
  13.    $string = addslashes($string);
  14.   }
  15. }
  16. return $string;
  17. }
  18. //用法實例:
  19. $_COOKIE = c_addslashes($_COOKIE);
  20. $_POST   = c_addslashes($_POST);
  21. $_GET   = c_addslashes($_GET);

  22. //在公共檔案中加入
  23. if($_FILES){  
  24. foreach( $_FILES as $key => $_value )
  25. {
  26.   $_FILES[$key]['type'] =$_value['type'];   
  27. }
  28. if(substr($_FILES[$key]['type'],0,6) !='image/')
  29. {
  30.   exit;
  31. }
  32. }
複製程式碼


10. xss過濾函式

  1. /**
  2. * xss過濾函式
  3. *
  4. * @param $string
  5. * @return string
  6. */
  7. function remove_xss($string) {
  8. $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S|<|>', '', $string);
  9. $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  10. $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate',
  11. 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange',
  12. 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut',
  13. 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate',
  14. 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop',
  15. 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin',
  16. 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload',
  17. 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste',
  18. 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend',
  19. 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll',
  20. 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit',
  21. 'onunload');
  22. $parm = array_merge($parm1, $parm2);
  23. for ($i = 0; $i < sizeof($parm); $i++) {
  24.   $pattern = '/';
  25.   for ($j = 0; $j < strlen($parm[$i]); $j++) {
  26.    if ($j > 0) {
  27.     $pattern .= '(';
  28.     $pattern .= '(&#[x|X]0([9][a][b]);?)?';
  29.     $pattern .= '|(�([9][10][13]);?)?';
  30.     $pattern .= ')?';
  31.    }
  32.    $pattern .= $parm[$i][$j];
  33.   }
  34.   $pattern .= '/i';
  35.   $string = preg_replace($pattern, ' ', $string);
  36. }
  37. return $string;
  38. }
複製程式碼


11. 過濾ASCII碼從0-28的控制字元

  1. /**
  2. * 實用
  3. * 過濾ASCII碼從0-28的控制字元
  4. * @return String
  5. */
  6. function trim_unsafe_control_chars($str) {
  7. $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
  8. return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
  9. }

  10. echo trim_unsafe_control_chars(" asdasdas</script>");
  11. echo "<br>";
複製程式碼


12.格式化文字欄位內容

  1. /**
  2. * 格式化文字欄位內容
  3. *
  4. * @param $string 文字欄位內容
  5. * @return string
  6. */
  7. function trim_textarea($string) {
  8. $string = nl2br ( str_replace ( ' ', ' ', $string ) );
  9. return $string;
  10. }
  11. echo trim_textarea("<a> asc sda  sdas</a>");
  12. echo "<br>";
複製程式碼


13.將文字格式成適合js輸出的字串

  1. /**
  2. * 將文字格式成適合js輸出的字串
  3. * @param string $string 需要處理的字串
  4. * @param intval $isjs 是否執行字串格式化,預設為執行
  5. * @return string 處理後的字串
  6. */
  7. function format_js($string, $isjs = 1) {
  8. $string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
  9. return $isjs ? 'document.write("'.$string.'");' : $string;
  10. }
  11. echo format_js("<a> asc sda  sdas</a>");
  12. echo "<br>";
複製程式碼


14.獲得完整URL地址

  1. /**
  2. * 實用
  3. * 獲得完整URL地址
  4. */
  5. function get_url() {
  6. $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
  7. $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
  8. $path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
  9. $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
  10. return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
  11. }


  12. echo get_url();

  13. echo "<br>";
複製程式碼


15.獲得 ip

  1. /**
  2. * 實用
  3. * 獲得 ip
  4. *
  5. * @return ip地址
  6. */
  7. function ip() {
  8. if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  9.   $ip = getenv('HTTP_CLIENT_IP');
  10. } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  11.   $ip = getenv('HTTP_X_FORWARDED_FOR');
  12. } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  13.   $ip = getenv('REMOTE_ADDR');
  14. } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  15.   $ip = $_SERVER['REMOTE_ADDR'];
  16. }
  17. return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
  18. }
  19. function get_cost_time() {
  20. $microtime = microtime ( TRUE );
  21. return $microtime - SYS_START_TIME;
  22. }


  23. echo ip();
  24. echo "<br>";
複製程式碼


16.範本調用

  1. /**
  2. * 範本調用
  3. *
  4. * @param $module
  5. * @param $template
  6. * @param $istag
  7. * @return unknown_type
  8. */
  9. function template($module = 'content', $template = 'index', $style = '') {
  10. if(strpos($module, 'plugin/')!== false) {
  11.   $plugin = str_replace('plugin/', '', $module);
  12.   return p_template($plugin, $template,$style);
  13. }
  14. $module = str_replace('/', DIRECTORY_SEPARATOR, $module);
  15. if(!empty($style) && preg_match('/([a-z0-9\-_]+)/is',$style)) {
  16. } elseif (empty($style) && !defined('STYLE')) {
  17.   if(defined('SITEID')) {
  18.    $siteid = SITEID;
  19.   } else {
  20.    $siteid = param::get_cookie('siteid');
  21.   }
  22.   if (!$siteid) $siteid = 1;
  23.   $sitelist = getcache('sitelist','commons');
  24.   if(!empty($siteid)) {
  25.    $style = $sitelist[$siteid]['default_style'];
  26.   }
  27. } elseif (empty($style) && defined('STYLE')) {
  28.   $style = STYLE;
  29. } else {
  30.   $style = 'default';
  31. }
  32. if(!$style) $style = 'default';
  33. $template_cache = app_base::load_sys_class('template_cache');
  34. $compiledtplfile = ROOT_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
  35. if(file_exists(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
  36.   if(!file_exists($compiledtplfile) || (@filemtime(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) {
  37.    $template_cache->template_compile($module, $template, $style);
  38.   }
  39. } else {
  40.   $compiledtplfile = ROOT_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
  41.   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))) {
  42.    $template_cache->template_compile($module, $template, 'default');
  43.   } elseif (!file_exists(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
  44.    showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
  45.   }
  46. }
  47. return $compiledtplfile;
  48. }
複製程式碼


17.計算字元數的大小單位

  1. /**
  2. * 實用
  3. * 計算字元數的大小單位
  4. *
  5. *
  6. * @param string $filesize 字元大小
  7. * @return string 返回大小
  8. */
  9. function sizecount($filesize) {
  10. if ($filesize >= 1073741824) {
  11.   $filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
  12. } elseif ($filesize >= 1048576) {
  13.   $filesize = round($filesize / 1048576 * 100) / 100 .' MB';
  14. } elseif($filesize >= 1024) {
  15.   $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
  16. } else {
  17.   $filesize = $filesize.' Bytes';
  18. }
  19. return $filesize;
  20. }

  21. echo sizecount(35632454);
  22. echo "<br>";
複製程式碼


18.字串加密、解密

  1. /**
  2. * 實用
  3. * 字串加密、解密函式
  4. *
  5. *
  6. * @param string $txt  字串
  7. * @param string $operation ENCODE為加密,DECODE為解密,可選參數,預設為ENCODE,
  8. * @param string $key  金鑰:數字、字母、底線
  9. * @param string $expiry  到期時間
  10. * @return string
  11. */
  12. function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
  13.         $key_length = 4;
  14.         $key = md5($key != '' ? $key : app_base::load_config('system', 'auth_key'));
  15.         $fixedkey = md5($key);
  16.         $egiskeys = md5(substr($fixedkey, 16, 16));
  17.         $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
  18.         $keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
  19.         $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
  20.         $i = 0; $result = '';
  21.         $string_length = strlen($string);
  22.         for ($i = 0; $i < $string_length; $i++){
  23.                   $result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
  24.         }
  25.         if($operation == 'ENCODE') {
  26.                   return $runtokey . str_replace('=', '', base64_encode($result));
  27.         }
  28.         else {
  29.                   if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
  30.                            return substr($result, 26);
  31.                   }
  32.                   else
  33.                   {
  34.                            return '';
  35.                   }
  36.         }
  37. }

  38. $a1 = sys_auth("liman123456789aaaaa阿薩德//dsas",'ENCODE','manasdas123',1);
  39. echo $a1."<br>";

  40. $a2 = sys_auth($a1,'DECODE','manasdas123',1);
  41. echo $a2."<br>";
複製程式碼


19.查詢字元是否存在於某字串

  1. /**
  2. * 查詢字元是否存在於某字串
  3. *
  4. * @param $haystack 字串
  5. * @param $needle 要尋找的字元
  6. * @return bool
  7. */
  8. function str_exists($haystack, $needle)
  9. {
  10. return !(strpos($haystack, $needle) === FALSE);
  11. }

  12. echo str_exists('liman','c');
  13. echo "<br>";
複製程式碼


20.取得檔案副檔名

  1. /**
  2. *實用
  3. *
  4. * 取得檔案副檔名
  5. *
  6. * @param $filename 檔案名稱
  7. * @return 副檔名
  8. */
  9. function fileext($filename) {
  10. return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
  11. }

  12. echo fileext('liman.c');
  13. echo "<br>";
複製程式碼


20.加載範本標籤快取

  1. /**
  2. * 加載範本標籤快取
  3. * @param string $name 快取名
  4. * @param integer $times 快取時間
  5. */
  6. function tpl_cache($name,$times = 0) {
  7. $filepath = 'tpl_data';
  8. $info = getcacheinfo($name, $filepath);
  9. if (SYS_TIME - $info['filemtime'] >= $times) {
  10.   return false;
  11. } else {
  12.   return getcache($name,$filepath);
  13. }
  14. }
複製程式碼


21. 寫入快取,預設是檔案快取,不預讀快取設定。

  1. /**
  2. * 寫入快取,預設是檔案快取,不讀入快取設定。
  3. * @param $name 快取名稱
  4. * @param $data 快取資料
  5. * @param $filepath 資料路徑(模組名稱) caches/cache_$filepath/
  6. * @param $type 快取類型[file,memcache,apc]
  7. * @param $config 設定名稱
  8. * @param $timeout 到期時間
  9. */
  10. function setcache($name, $data, $filepath='', $type='file', $c ='AND ', $in_column = false) {
  11. if($in_column && is_array($data)) {
  12.   $ids = '\''.implode('\',\'', $data).'\'';
  13.   $sql = "$in_column IN ($ids)";
  14.   return $sql;
  15. } else {
  16.   if ($front == '') {
  17.    $front = ' AND ';
  18.   }
  19.   if(is_array($data) && count($data) > 0) {
  20.    $sql = '';
  21.    foreach ($data as $key => $val) {
  22.     $sql .= $sql ? " $front $key = '$val' " : " $key = '$val' ";
  23.    }
  24.    return $sql;
  25.   } else {
  26.    return $data;
  27.   }
  28. }
  29. }
複製程式碼


22.判斷email格式是否正確

  1. /**
  2. * 判斷email格式是否正確
  3. * @param $email
  4. */
  5. function is_email($email) {
  6. return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
  7. }
複製程式碼


23.iconv 編輯轉換

  1. /**
  2. * iconv 編輯轉換
  3. */
  4. if (!function_exists('iconv')) {
  5. function iconv($in_charset, $out_charset, $str) {
  6.   $in_charset = strtoupper($in_charset);
  7.   $out_charset = strtoupper($out_charset);
  8.   if (function_exists('mb_convert_encoding')) {
  9.    return mb_convert_encoding($str, $out_charset, $in_charset);
  10.   } else {
  11.    app_base::load_sys_func('iconv');
  12.    $in_charset = strtoupper($in_charset);
  13.    $out_charset = strtoupper($out_charset);
  14.    if ($in_charset == 'UTF-8' && $out_charset == 'BIG5') {
  15.     return utf8_to_big5($str);
  16.    }
  17.    if ($in_charset == 'BIG5' && $out_charset == 'UTF-8') {
  18.     return big5_to_utf8($str);
  19.    }
  20.    return $str;
  21.   }
  22. }
  23. }
複製程式碼


24.檔案下載

  1. /**
  2. * 檔案下載
  3. * @param $filepath 檔案路徑
  4. * @param $filename 檔案名稱
  5. */
  6. function file_down($filepath, $filename = '') {
  7. if(!$filename) $filename = basename($filepath);
  8. if(is_ie()) $filename = rawurlencode($filename);
  9. $filetype = fileext($filename);
  10. $filesize = sprintf("%u", filesize($filepath));
  11. if(ob_get_length() !== false) @ob_end_clean();
  12. header('Pragma: public');
  13. header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
  14. header('Cache-Control: no-store, no-cache, must-revalidate');
  15. header('Cache-Control: pre-check=0, post-check=0, max-age=0');
  16. header('Content-Transfer-Encoding: binary');
  17. header('Content-Encoding: none');
  18. header('Content-type: '.$filetype);
  19. header('Content-Disposition: attachment; filename="'.$filename.'"');
  20. header('Content-length: '.$filesize);
  21. readfile($filepath);
  22. exit;
  23. }
複製程式碼


25.產生縮略圖

  1. /**
  2. * 產生縮略圖
  3. * @param $imgurl 圖路徑
  4. * @param $width 縮略圖寬度
  5. * @param $height 縮略圖高度
  6. * @param $autocut 是否自動裁切 預設裁切,當高度或寬度有一個為0是,自動關閉
  7. * @param $smallpic 無圖片時使用預設圖片路徑
  8. */
  9. function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif') {
  10. global $image;
  11. $upload_url = app_base::load_config('system','upload_url');
  12. $upload_path = app_base::load_config('system','upload_path');
  13. if(empty($imgurl)) return IMG_PATH.$smallpic;
  14. $imgurl_replace= str_replace($upload_url, '', $imgurl);
  15. if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;
  16. if(!file_exists($upload_path.$imgurl_replace)) return IMG_PATH.$smallpic;
  17. list($width_t, $height_t, $type, $attr) = getimagesize($upload_path.$imgurl_replace);
  18. if($width>=$width_t || $height>=$height_t) return $imgurl;
  19. $newimgurl = dirname($imgurl_replace).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl_replace);
  20. if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;
  21. if(!is_object($image)) {
  22.   app_base::load_sys_class('image','','0');
  23.   $image = new image(1,0);
  24. }
  25. return $image->thumb($upload_path.$imgurl_replace, $upload_path.$newimgurl, $width, $height, '', $autocut) ? $upload_url.$newimgurl : $imgurl;
  26. }
複製程式碼


26.給圖加上水印

  1. /**
  2. * 給圖加上水印
  3. * @param $source 原圖路徑
  4. * @param $target 水印圖路徑,預設空,覆蓋原圖
  5. * @param $siteid 網站id,系統需根依據據網站id獲得水印資料
  6. */
  7. function watermark($source, $target = '',$siteid) {
  8. global $image_w;
  9. if(empty($source)) return $source;
  10. if(!extension_loaded('gd') || strpos($source, '://')) return $source;
  11. if(!$target) $target = $source;
  12. if(!is_object($image_w)){
  13.   app_base::load_sys_class('image','','0');
  14.   $image_w = new image(0,$siteid);
  15. }
  16.   $image_w->watermark($source, $target);
  17. return $target;
  18. }
複製程式碼


27.將附件地址轉換為實際地址

  1. /**
  2. * 將附件地址轉換為實際地址
  3. * @param $path 附件地址
  4. */
  5. function atturl($path) {
  6. if(strpos($path, ':/')) {
  7.   return $path;
  8. } else {
  9.   $sitelist = getcache('sitelist','commons');
  10.   $siteid = get_siteid();
  11.   $siteurl = $sitelist[$siteid]['domain'];
  12.   $domainlen = strlen($sitelist[$siteid]['domain'])-1;
  13.   $path = $siteurl.$path;
  14.   $path = substr_replace($path, '/', strpos($path, '//',$domainlen),2);
  15.   return  $path;
  16. }
  17. }
複製程式碼


28.驗證碼

  1. /*
  2. 驗證碼
  3. */
  4. session_start();
  5. Header("Content-type: image/gif");
  6. class SecurityCode
  7. {
  8. private $codes = '';
  9. function __construct()
  10. {
  11. $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';
  12. $codeArray = explode('-',$code);
  13. shuffle($codeArray);
  14. $this->codes = implode('',array_slice($codeArray,0,4));
  15. }
  16. public function CreateImg()
  17. {
  18. $_SESSION['check_pic'] = $this->codes;
  19. $img = imagecreate(70,25);
  20. imagecolorallocate($img,222,222,222);
  21. $testcolor1 = imagecolorallocate($img,255,0,0);
  22. $testcolor2 = imagecolorallocate($img,51,51,51);
  23. $testcolor3 = imagecolorallocate($img,0,0,255);
  24. $testcolor4 = imagecolorallocate($img,255,0,255);
  25. for ($i = 0; $i < 4; $i++)
  26. {
  27. imagestring($img,rand(5,6),8 + $i * 15,rand(2,8),$this->codes[$i],rand(1,4));
  28. }
  29. imagegif($img);
  30. }
  31. }
  32. $code = new SecurityCode();
  33. $code->CreateImg();
  34. $code = NULL;
複製程式碼


安全策略

  1. 1、php一些安全設定
  2. (1)關閉php提示錯誤功能
  3. (2)關閉一些「壞功能」
  4. (3)嚴格設定檔案權限。
  5. 2、嚴格的資料驗證,你的用戶不全是「好」人
  6. 2.1為了確保程序的安全性,健壯性,資料驗證應該包括內容。
  7. 2.2程序員容易漏掉point或者說需要注意的事項
  8. 3、防注入
  9.    3.1簡單判斷是否有注入漏洞以及原理
  10.    3.2常見的mysql注入語句
  11.        (1)不用用戶名和密碼
  12.        (2)在不輸入密碼的情況下,利用某用戶
  13.        (3)猜解某用戶密碼
  14. (4)插入資料時提權
  15. (5)更新提權和插入提權同理
  16. (6)惡意更新和刪除
  17. (7)union、join等
  18. (8)萬用字元%、_
  19. (9)還有很多猜測表資訊的注入sql
  20.    33防注入的一些方法
  21.        2.3.1 php可用於防注入的一些函式和注意事項。
  22.        2.3.2防注入字元優先級。
  23. 2.3.3防注入程式碼
  24.     (1)參數是數字直接用intval()函式
  25.     (2)對於非文字參數的過濾
  26. (3)文字資料防注入程式碼。
  27. (4)當然還有其他與addslashes、mysql_escape_string結合的程式碼。
  28. 4、防止xss攻擊
  29. 4.1Xss攻擊過程
  30. 4.2常見xss攻擊地方
  31. 4.3防XSS方法
  32. 5、CSRF
  33. 5.1簡單說明CSRF原理
  34. 5.2防範方法
  35. 6、防盜連
  36. 7、防拒CC攻擊


  37. php一些安全設定

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

  41. 在php.ini 把magic_quotes_gpc = OFF
  42. 避免和addslashes等重複跳脫

  43. 在php.ini 把register_globals = OFF

  44. 確保對 SQL 語句的所有用戶輸入進行跳脫。




  45. 將 PHP 的內置 mysql_real_escape_string() 函式用作任何用戶輸入的容器。這個函式對字串中的字元進行跳脫,使字串不可能傳遞撇號等特殊字元並讓 MySQL 根據特殊字元進行操作。清單 7 展示了帶轉義處理的程式碼。

  46. 不安全
  47. $sql = 「select count(*) as ctr from users where username='」.$username.」' and password='」. $pw.」' limit 1〞;

  48. 安全
  49. $sql = 「select count(*) as ctr from users where username='」.mysql_real_escape_string($username).」' and password='」. mysql_real_escape_string($pw).」' limit 1〞;


  50. $Exec_Commond  = "( \\s|\\S)*(exec(\\s|\\+)+(s|x)p\\w+)(\\s|\\S)*";
  51. $Simple_XSS = "( \\s|\\S)*((%3C)|<)((%2F)|/)*[a-z0-9%]+((%3E)|>)(\\s|\\S)*";
  52. $Eval_XSS  = "( \\s|\\S)*((%65)|e)(\\s)*((%76)|v)(\\s)*((%61)|a)(\\s)*((%6C)|l)(\\s|\\S)*";
  53. $Image_XSS  = "( \\s|\\S)*((%3C)|<)((%69)|i|I|(%49))((%6D)|m|M|(%4D))((%67)|g|G|(%47))[^\\n]+((%3E)|>)(\\s|\\S)*" ;
  54. $Script_XSS = "( \\s|\\S)*((%73)|s)(\\s)*((%63)|c)(\\s)*((%72)|r)(\\s)*((%69)|i)(\\s)*((%70)|p)(\\s)*((%74)|t)(\\s|\\S)*";
  55. $SQL_Injection = "( \\s|\\S)*((%27)|(')|(%3D)|(=)|(/)|(%2F)|(")|((%22)|(-|%2D){2})|(%23)|(%3B)|(;))+(\\s|\\S)*";
複製程式碼
作者文章推薦
懶得打字嗎?讓本助手協助你 【使用進階編輯器請點選右方進階模式】
您需要登入後才可以回覆 登入 | 註冊

本版積分規則

手機版|Archiver|漁家小舖

GMT+8, 2024年5月2日 18:48 , Processed in 0.365066 second(s), 17 queries , Gzip On, Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回覆 返回頂端 返回清單