PHP 常用到的函数

jopen 12年前

<?php      //获得当前的脚本网址  function GetCurUrl()  {  if(!empty($_SERVER["REQUEST_URI"]))  {  $scriptName = $_SERVER["REQUEST_URI"];  $nowurl = $scriptName;  }  else{  $scriptName = $_SERVER["PHP_SELF"];  if(empty($_SERVER["QUERY_STRING"]))  {  $nowurl = $scriptName;  }  else{  $nowurl = $scriptName."?".$_SERVER["QUERY_STRING"];  }  }  return $nowurl;  }      //将URL中的某参数设为某值    function url_set_value($url,$key,$value)  {  $a=explode('?',$url);  $url_f=$a[0];  $query=$a[1];  parse_str($query,$arr);  $arr[$key]=$value;  return $url_f.'?'.http_build_query($arr);  }      //获取IP  function GetIP() {      if ($_SERVER["HTTP_X_FORWARDED_FOR"])          $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];      else if ($_SERVER["HTTP_CLIENT_IP"])          $ip = $_SERVER["HTTP_CLIENT_IP"];      else if ($_SERVER["REMOTE_ADDR"])          $ip = $_SERVER["REMOTE_ADDR"];      else if (getenv("HTTP_X_FORWARDED_FOR"))          $ip = getenv("HTTP_X_FORWARDED_FOR");      else if (getenv("HTTP_CLIENT_IP"))          $ip = getenv("HTTP_CLIENT_IP");      else if (getenv("REMOTE_ADDR"))          $ip = getenv("REMOTE_ADDR");      else          $ip = "Unknown";      return $ip;  }      //时间的增加(还可以改进成时分秒都可以增加,有时间再补上)  function DateAdd($date, $int, $unit = "d") {      $dateArr = explode("-", $date);      $value[$unit] = $int;      return date("Y-m-d", mktime(0,0,0, $dateArr[1] + $value['m'], $dateArr[2] + $value['d'], $dateArr[0] + $value['y'])); //oSPHP.COM.CN  }      //计算出给出的日期是星期几  function GetWeekDay($date) {      $dateArr = explode("-", $date);      return date("w", mktime(0,0,0,$dateArr[1],$dateArr[2],$dateArr[0]));  }      //检查日期是否合法日期  function check_date($date) {      $dateArr = explode("-", $date);      if (is_numeric($dateArr[0]) && is_numeric($dateArr[1]) && is_numeric($dateArr[2])) {          return checkdate($dateArr[1],$dateArr[2],$dateArr[0]);      }      return false;  }      //检查时间是否合法时间  function check_time($time) {      $timeArr = explode(":", $time);      if (is_numeric($timeArr[0]) && is_numeric($timeArr[1]) && is_numeric($timeArr[2])) {          if (($timeArr[0] >= 0 && $timeArr[0] <= 23) && ($timeArr[1] >= 0 && $timeArr[1] <= 59) && ($timeArr[2] >= 0 && $timeArr[2] <= 59))              return true;          else              return false;      }      return false;  }  //时间比较函数,返回两个日期相差几秒、几分钟、几小时或几天  function DateDiff($date1, $date2, $unit = "") {      switch ($unit) {          case 's':              $dividend = 1;              break;          case 'i':              $dividend = 60;              break;          case 'h':              $dividend = 3600;              break;          case 'd':              $dividend = 86400;              break;          default:              $dividend = 86400;      }      $time1 = strtotime($date1);      $time2 = strtotime($date2);      if ($time1 && $time2) //OSPHP.com.CN          return (float)($time1 - $time2) / $dividend;      return false;  }  //获取访问者浏览器  function browse_infor()  {  $browser="";$browserver="";  $Browsers =array("Lynx","MOSAIC","AOL","Opera","JAVA","MacWeb","WebExplorer","OmniWeb");  $Agent = $GLOBALS["HTTP_USER_AGENT"];  for ($i=0; $i<=7; $i++)  {  if (strpos($Agent,$Browsers[$i]))  {  $browser = $Browsers[$i];  $browserver ="";  }  }  if (ereg("Mozilla",$Agent) && !ereg("MSIE",$Agent))  {  $temp =explode("(", $Agent); $Part=$temp[0];  $temp =explode("/", $Part); $browserver=$temp[1];  $temp =explode(" ",$browserver); $browserver=$temp[0];  $browserver =preg_replace("/([d.]+)/","1",$browserver);  $browserver = " $browserver";  $browser = "Netscape Navigator";  }  if (ereg("Mozilla",$Agent) && ereg("Opera",$Agent))  {  $temp =explode("(", $Agent); $Part=$temp[1];  $temp =explode(")", $Part); $browserver=$temp[1];  $temp =explode(" ",$browserver);$browserver=$temp[2];  $browserver =preg_replace("/([d.]+)/","1",$browserver);  $browserver = " $browserver";  $browser = "Opera";  }  if (ereg("Mozilla",$Agent) && ereg("MSIE",$Agent))  {  $temp = explode("(", $Agent); $Part=$temp[1];  $temp = explode(";",$Part); $Part=$temp[1];  $temp = explode(" ",$Part);$browserver=$temp[2];  $browserver =preg_replace("/([d.]+)/","1",$browserver);  $browserver = " $browserver";  $browser = "Internet Explorer";  }  if ($browser!="")  {  $browseinfo = "$browser$browserver";  }  else{  $browseinfo = "Unknown";  }  return $browseinfo;  }  //调用方法$browser=browseinfo() ;直接返回结果      //获取访问者操作系统  function osinfo() {  $os="";  $Agent = $GLOBALS["HTTP_USER_AGENT"];  if (eregi('win',$Agent) && strpos($Agent, '95')) {  $os="Windows 95";  }  elseif (eregi('win 9x',$Agent) && strpos($Agent, '4.90')) {  $os="Windows ME";  }  elseif (eregi('win',$Agent) && ereg('98',$Agent)) {  $os="Windows 98";  }  elseif (eregi('win',$Agent) && eregi('nt 5.0',$Agent)) {  $os="Windows 2000";  }  elseif (eregi('win',$Agent) && eregi('nt',$Agent)) {  $os="Windows NT";  }  elseif (eregi('win',$Agent) && eregi('nt 5.1',$Agent)) {  $os="Windows XP";  }  elseif (eregi('win',$Agent) && ereg('32',$Agent)) {  $os="Windows 32";  }  elseif (eregi('linux',$Agent)) {  $os="Linux";  }  elseif (eregi('unix',$Agent)) {  $os="Unix";  }  elseif (eregi('sun',$Agent) && eregi('os',$Agent)) {  $os="SunOS";  }  elseif (eregi('ibm',$Agent) && eregi('os',$Agent)) {  $os="IBM OS/2";  }  elseif (eregi('Mac',$Agent) && eregi('PC',$Agent)) {  $os="Macintosh";  }  elseif (eregi('PowerPC',$Agent)) {  $os="PowerPC";  }  elseif (eregi('AIX',$Agent)) {  $os="AIX";  }  elseif (eregi('HPUX',$Agent)) {  $os="HPUX";  }  elseif (eregi('NetBSD',$Agent)) {  $os="NetBSD";  }  elseif (eregi('BSD',$Agent)) {  $os="BSD";  }  elseif (ereg('OSF1',$Agent)) {  $os="OSF1";  }  elseif (ereg('IRIX',$Agent)) {  $os="IRIX";  }  elseif (eregi('FreeBSD',$Agent)) {  $os="FreeBSD";  }  if ($os=='') $os = "Unknown";  return $os;  }  //调用方法$os=os_infor() ;      //页面快速转向  function turntopage($url="index.php",$info = "页面转向中...",$second=2){  print "<html>n<head>n<title>页面转向中....</title>n";  print "<meta http-equiv="refresh" content="$second;url=$url">n";  print "<style type="text/css">n<!--n";  print "td { font-family: "Verdana", "Arial";font-size: 12px}n";  print "A {COLOR: #000000; TEXT-DECORATION: none}n";  print "-->n</style>n";  print "</head>n<body>n";  print "<table width="100%" border="0" align="center">n";  print " <tr>n";  print " <td height="200"> </td>n";  print " </tr>n";  print " <tr>n";  print " <td align="center">n";  print " <table width="60%" border="0" cellpadding="8" bgcolor="#AA9FFF">n";  print " <tr>n";  print " <td height="30" align="center">页面转向提示信息</td>n";  print " </tr>n";  print " <tr>n";  print " <td align="center">$info</td>n";  print " </tr>n";  print " <tr>n";  print " <td align="center">n";  print " <a href="$url">如果你的浏览器不支持自动跳转,请按这里</a></td>n";  print " </tr>n";  print " </tr>n";  print " </table></td>n";  print " </tr>n";  print " <tr>n";  print " <td height="200"> </td>n";  print " </tr>n";  print "</table>n";  print "</body>n</html>";  exit;  }      /**   * 返回经addslashes处理过的字符串或数组   * @param $string 需要处理的字符串或数组   * @return mixed   */  function new_addslashes($string){  if(!is_array($string)) return addslashes($string);  foreach($string as $key => $val) $string[$key] = new_addslashes($val);  return $string;  }      /**   * 返回经stripslashes处理过的字符串或数组   * @param $string 需要处理的字符串或数组   * @return mixed   */  function new_stripslashes($string) {  if(!is_array($string)) return stripslashes($string);  foreach($string as $key => $val) $string[$key] = new_stripslashes($val);  return $string;  }      /**   * 返回经addslashe处理过的字符串或数组   * @param $obj 需要处理的字符串或数组   * @return mixed   */  function new_html_special_chars($string) {  if(!is_array($string)) return htmlspecialchars($string);  foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);  return $string;  }  /**   * 安全过滤函数   *   * @param $string   * @return string   */  function safe_replace($string) {  $string = str_replace('%20','',$string);  $string = str_replace('%27','',$string);  $string = str_replace('%2527','',$string);  $string = str_replace('*','',$string);  $string = str_replace('"','&quot;',$string);  $string = str_replace("'",'',$string);  $string = str_replace('"','',$string);  $string = str_replace(';','',$string);  $string = str_replace('<','&lt;',$string);  $string = str_replace('>','&gt;',$string);  $string = str_replace("{",'',$string);  $string = str_replace('}','',$string);  return $string;  }              /**   * 过滤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 ) );  }      /**   * 格式化文本域内容   *   * @param $string 文本域内容   * @return string   */  function trim_textarea($string) {  $string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );  return $string;  }      /**   * 将文本格式成适合js输出的字符串   * @param string $string 需要处理的字符串   * @param intval $isjs 是否执行字符串格式化,默认为执行   * @return string 处理后的字符串   */  function format_js($string, $isjs = 1){  $string = addslashes(str_replace(array("\r", "\n"), array('', ''), $string));  return $isjs ? 'document.write("'.$string.'");' : $string;  }      /**   * 转义 javascript 代码标记   *   * @param $str   * @return mixed   */  function trim_script($str) {  $str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );  $str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );  $str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );  $str = preg_replace ( '/]]\>/si', ']] >', $str );  return $str;  }      /**   * 字符截取 支持UTF8/GBK   * @param $string   * @param $length   * @param $dot   */  function str_cut($string, $length, $dot = '...') {  $strlen = strlen($string);  if($strlen <= $length) return $string;  $string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);  $strcut = '';  if(strtolower(CHARSET) == 'utf-8') {  $length = intval($length-strlen($dot)-$length/3);  $n = $tn = $noc = 0;  while($n < strlen($string)) {  $t = ord($string[$n]);  if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {  $tn = 1; $n++; $noc++;  } elseif(194 <= $t && $t <= 223) {  $tn = 2; $n += 2; $noc += 2;  } elseif(224 <= $t && $t <= 239) {  $tn = 3; $n += 3; $noc += 2;  } elseif(240 <= $t && $t <= 247) {  $tn = 4; $n += 4; $noc += 2;  } elseif(248 <= $t && $t <= 251) {  $tn = 5; $n += 5; $noc += 2;  } elseif($t == 252 || $t == 253) {  $tn = 6; $n += 6; $noc += 2;  } else {  $n++;  }  if($noc >= $length) {  break;  }  }  if($noc > $length) {  $n -= $tn;  }  $strcut = substr($string, 0, $n);  $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);  }  else {  $dotlen = strlen($dot);  $maxi = $length - $dotlen - 1;  $current_str = '';  $search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');  $replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');  $search_flip = array_flip($search_arr);  for ($i = 0; $i < $maxi; $i++) {  $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];  if (in_array($current_str, $search_arr)) {  $key = $search_flip[$current_str];  $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);  }  $strcut .= $current_str;  }  }  return $strcut.$dot;  }      /**   * 获取请求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] : '';  }      /**   * 程序执行时间   *   * @returnint单位ms   */  function execute_time() {  $stime = explode ( ' ', SYS_START_TIME );  $etime = explode ( ' ', microtime () );  return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );  }      /**  * 产生随机字符串  *  * @param    int        $length  输出长度  * @param    string     $chars   可选的 ,默认为 0123456789  * @return   string     字符串  */  function random($length, $chars = '0123456789') {  $hash = '';  $max = strlen($chars) - 1;  for($i = 0; $i < $length; $i++) {  $hash .= $chars[mt_rand(0, $max)];  }  return $hash;  }      /**  * 将字符串转换为数组  *  * @paramstring$data字符串  * @returnarray返回数组格式,如果,data为空,则返回空数组  */  function string2array($data) {  if($data == '') return array();  eval("\$array = $data;");  return $array;  }  /**  * 将数组转换为字符串  *  * @paramarray$data数组  * @parambool$isformdata如果为0,则不使用new_stripslashes处理,可选参数,默认为1  * @returnstring返回字符串,如果,data为空,则返回空  */  function array2string($data, $isformdata = 1) {  if($data == '') return '';  if($isformdata) $data = new_stripslashes($data);  return addslashes(var_export($data, TRUE));  }      /**  * 转换字节数为其他单位  *  *  * @paramstring$filesize字节大小  * @returnstring返回大小  */  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;  }      /**   * 查询字符是否存在于某字符串   *   * @param $haystack 字符串   * @param $needle 要查找的字符   * @return bool   */  function str_exists($haystack, $needle)  {  return !(strpos($haystack, $needle) === FALSE);  }      /**   * 取得文件扩展   *   * @param $filename 文件名   * @return 扩展名   */  function fileext($filename) {  return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));  }      /**   * 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c')   * @param $data 条件数组或者字符串   * @param $front 连接符   * @param $in_column 字段名称   * @return string   */  function to_sqls($data, $front = ' 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;  }  }  }      /**   * 判断email格式是否正确   * @param $email   */  function is_email($email) {  return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);  }      /**   * 文件下载   * @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;  }      /**   * 判断字符串是否为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);  }      /**   * 对用户的密码进行加密   * @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;  }      /**   * 生成随机字符串   * @param string $lenth 长度   * @return string 字符串   */  function create_randomstr($lenth = 6) {  return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');  }      /**   * 检查密码长度是否符合规定   *   * @param STRING $password   * @return TRUE or FALSE   */  function is_password($password) {  $strlen = strlen($password);  if($strlen >= 6 && $strlen <= 20) return true;  return false;  }       /**   * 检测输入中是否含有错误字符   *   * @param char $string 要检查的字符串名称   * @return TRUE or FALSE   */  function is_badword($string) {  $badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n","#");  foreach($badwords as $value){  if(strpos($string, $value) !== FALSE) {  return TRUE;  }  }  return FALSE;  }      /**   * 检查用户名是否符合规定   *   * @param STRING $username 要检查的用户名   * @return TRUE or FALSE   */  function is_username($username) {  $strlen = strlen($username);  if(is_badword($username) || !preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)){  return false;  } elseif ( 20 <= $strlen || $strlen < 2 ) {  return false;  }  return true;  }      /**   * 检查id是否存在于数组中   *   * @param $id   * @param $ids   * @param $s   */  function check_in($id, $ids = '', $s = ',') {  if(!$ids) return false;  $ids = explode($s, $ids);  return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);  }      /**   * 对数据进行编码转换   * @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;  }  }      ?>