常用函数

代码:

 

<?php
/************************************************************
*    Filename :  function file 2.0                            *
*    Address:    New York                                      *
*    Copyright (C) 2008-2010                                *
*************************************************************/ 

	// 防注入
	function inject($str) {
		if(!empty($str)){
			$pour=eregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|<|>|\"|union|into|load_file|outfile', $str);  
			if($pour){ 
				exit("<script>alert(' $str is wrong !');history.back(1)</script>"); 
			}else{ return $str; }
		}else{
			exit("<script>alert(' content is empty !');history.back(1)</script>");
		}
	}
	
	// 返回正整数
	function isint($str){
		if(!empty($str)){
			$pour=preg_match("/^[0-9]*[1-9][0-9]*$/",$str);  
			if($pour){ return $str; }else{ exit("<script>alert(' $str is wrong !');history.back(1)</script>"); }
		}else{
			exit("<script>alert(' Number is empty !');history.back(1)</script>");
		}
	}	
	
	// 截取字段
	function all_substr($str, $start, $length){   
		$pa="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|";   
		$pa.="\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";   
		preg_match_all($pa, $str, $t_string);   
		if(count($t_string[0]) - $start > $length){   
			return join('', array_slice($t_string[0], $start, $length)) . "...";   
		}else{   
			return join('', array_slice($t_string[0], $start, $length));   
		}   
	}  
	
	// 检测用户名
	function user($str,$tips){
		if(empty($str)){
			exit("<script>alert('".$tips." can not be empty !');history.back(1);</script>");
		}else{
			$pour=preg_match("/^[a-z0-9][a-z0-9_]{3,15}$/i", $str);
			if($pour){ return inject($str); }else{ exit("<script>alert(' Username is made up of 3 - 15 characters !');history.back(1)</script>"); }
		}
	}
	
	// 检测是否为空
	function is_empty($str,$tips){ 
		if(empty($str)){ 
			exit("<script>alert('".$tips." can not be empty !');history.back(1);</script>");
		}else{ 
			return inject($str); 
		} 
	}
	
	// 验证邮件地址
	function isEmail($str){
		$pour=preg_match("/^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$/i",$str); 
		 if($pour){
			 return $str;
		 }else{
			exit("<script>alert(' $str is wrong !');history.back(1)</script>");
		 }
	}
	
	//  验证是否为数组
	function is_arr($arr){ 
		if(is_array($arr)){ return $arr; }else{ exit("<script>alert(' No datas !');history.back(1)</script>"); }
	}

	
	// 返回图片
	function html_img($path,$add = '',$alt = '',$title = ''){
		if(!empty($alt)){ $alt = "alt=\"".$alt."\""; } if(!empty($title)){ $title = "title=\"".$title."\""; }
		return "<img src=\"".$path."\" ".$add." ".$alt." ".$title." />";	
	}
	
	// 返回链接
	function html_link($path,$title,$add = '',$target = ''){
		if(!empty($target)){ $target = "target=\"".$target."\""; }
		return "<a href=\"".$path."\" ".$target." ".$add.">".$title."</a>";	
	}
	
	// 返回地址
	function gotoUrl($url='',$tips=''){
		if(empty($url) && empty($tips)){
			exit("<script type=\"text/javascript\">history.back(1);</script>");
		}elseif(!empty($url) && empty($tips)){
			exit("<script type=\"text/javascript\">location='".$url."'</script>");
		}elseif(empty($url) && !empty($tips)){
			exit("<script type=\"text/javascript\">alert('".$tips."');history.back(1);</script>");
		}else{
			exit("<script type=\"text/javascript\">alert('".$tips."');location='".$url."'</script>");
		}
	}
	
	// 验证url地址
	function url($str){
	  return (preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/",$str))?true:"URL format error!";
	}
		
	// 获取html中图片的地址
	function getImg($str){
		$str = stripslashes($str);
		$pattern = "/<img[^>]*src\=\"(([^>]*)(jpg|gif|png|bmp|jpeg))\"/";   //获取所有图片标签的全部信息
		preg_match_all($pattern, $str, $matches);
	  
	    return $matches[1];   //$matches[1]中就是所想匹配的结果,结果为数组
	}
	
	// 非法字符
	function isvalidname($username){
		$badkey = array("\\", '|', ' ', ' ', "'", '"', '/', '*', ',', '~', ';', '<',
			'>', '$', "\r", "\t", "\n",'#','*','?',':','@','!','(',')','~','`','^','&');
		foreach ($badkey as $value){
			if (strpos($username, $value) !== false){
				return false;
				exit;
			}
		}
		return true;
	}	

	// 去除html标签
	function isbare($str){
		return strip_tags($str);
	}
	
	// 在指定的预定义字符前添加反斜杠
	function addline($str){
		return addslashes($str);	
	}
	
	// 去除预定义字符前添加反斜杠
	function delline($str){
		return stripslashes($str);	
	}
	
	// 截取字段
	function firstPath($str,$end){
		return substr( $str,0,strpos( $str, $end)) ;	
	}
	
	function lastPath($str,$end){
		return substr( $str,strrpos($str, $end)) ;	
	}
	
	// 返回路径中的文件名部分
	function urlName($path,$suffix){
		if(empty($suffix)){
			return basename($path);	 //显示带有文件扩展名的文件名
		}else{
			return basename($path,$suffix);	 //显示不带有文件扩展名的文件名
		}
	}
	
	// GD库是否开启
	function gd(){
	  if(extension_loaded('gd'))   {  
		  if(function_exists('gd_info'))   {  
			  echo '<pre>'; print_r(gd_info()); echo '</pre>'; exit; 
		  }else{ 
			  exit('OOOOPS, this GD Version is so low !');
		  }
	  }else  
		  exit(' We can not find GD !');  
	}
	
	// 返回图片信息
	function myimg($img,$btn = 0){
		$getinfor = @getimagesize($img);
		
		if($btn == 1){
			return $arr =  array($getinfor[0],$getinfor[1]);
		}elseif($btn == 2){
			switch($getinfor[2]){
				case 1: return 'gif'; break;
				case 2: return 'jpg'; break;
				case 3: return 'png'; break;
				case 6: return 'bmp'; break;
			}
		}else{
			echo '<pre>'; print_r($getinfor); echo '</pre>'; exit;
		}
	}
	
	// 打印函数
	function printer($arr,$add = 1){
		echo '<pre>'; if($add !=1 ){ var_dump($arr); }else{ print_r($arr); } echo '</pre>'; exit;
	}
	
	//返回结果为1只有数字,2只有字符,3两者都有
	function checkVS($str){
		$a=0; $b=0;
		for($i=0;$i<strlen($str);$i++){
			$v=ord(substr($str,$i,1));
			if($v>=48 and $v<=57){
				$a=1;
			}else{
				$b=2;
			}
		}
		return $a+$b; 
	}

	// 返回数组中最大值
	function maxi($arr){
		sort($arr);
		return $arr[count($arr)-1];
	}
	
	// 删除文件夹目录(允许有多级目录)
    	/*****
	*@dir - Directory to destroy
	*@virtual[optional]- whether a virtual directory
	*/
	function destroyDir($dir, $virtual = false)
	{
		$ds = DIRECTORY_SEPARATOR;
		$dir = $virtual ? realpath($dir) : $dir;
		$dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
		if (is_dir($dir) && $handle = opendir($dir))
		{
			while ($file = readdir($handle))
			{
				if ($file == '.' || $file == '..')
				{
					continue;
				}
				elseif (is_dir($dir.$ds.$file))
				{
					destroyDir($dir.$ds.$file);
				}
				else
				{
					unlink($dir.$ds.$file);
				}
			}
			closedir($handle);
			rmdir($dir);
			return true;
		}
		else
		{
			return false;
		}
	}

	// 列出目录内容 $dir 不要加 '/'
	function list_files($dir)
	{
		if(is_dir($dir))
		{
			if($handle = opendir($dir))
			{
				while(($file = readdir($handle)) !== false)
				{
					if($file != "." && $file != ".." && $file != "Thumbs.db")
					{
						echo '<a target="_blank" href="'.$dir.'/'.$file.'">'.$file.'</a><br>'."\n";
					}
				}
				closedir($handle);
			}
		}
	}
	
	// 删除指定文件
	function delFile($path){
		if(is_file($path)){
			 @unlink($path);
		}
	}
	
	// 移动(目录要存在)或者修改名字
	function moveFile($oldName,$newName){
		@rename($oldName,$newName);
	}
	
	// 创建相应的文件夹
	function createdir($dir=''){
		if (!is_dir($dir)){
			$temp = explode('/',$dir);
			$cur_dir = '';
			for($i=0;$i<count($temp);$i++){
				$cur_dir .= $temp[$i].'/';
				if (!is_dir($cur_dir)){
					@mkdir($cur_dir,0777);
				}
			}
		}
	}
	
	//  IP 地址
	function getip(){ 
		if(getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){
			$ip = getenv("HTTP_CLIENT_IP"); 
		}else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){
			$ip = getenv("HTTP_X_FORWARDED_FOR"); 
		}else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")){
			$ip = getenv("REMOTE_ADDR"); 
		}else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){
			$ip = $_SERVER['REMOTE_ADDR']; 
		}else{
			$ip = "unknown"; 		
		}
		return($ip);
	}
	
	// 跳转
	function flyTo($title='',$message='',$url=''){
		$html  ="<html><head>";
		if(!empty($url)){
			$html .="<meta http-equiv='refresh' content=\"3;url='".$url."'\">";
			//$html .="<link href='../templates/style.css' type=text/css rel=stylesheet><style type='text/css'>";
			$html .="<style type='text/css'>";
			$html .="*{font-family:Arial, Helvetica, sans-serif; font-size:13px;} table{border-collapse:collapse;} .m_title{background:#DADAFF;} .line_1{background:#FFFAF6;}";
			$html .="</style></head><body><br><br>";
			$html .="<table cellspacing='0' cellpadding='0' border='1' width='450' align='center'>";
			$html .="<tr><td bgcolor='#ffffff'>";
			$html .="<table border='1' cellspacing='1' cellpadding='4' width='100%'>";
			$html .="<tr class='m_title'>";
			$html .="<td>".$title."</td></tr>";
			$html .="<tr class='line_1'><td align='center' height='60'>";
			$html .="<br>".$message."<br><br>";
			$html .="The system will return in 3 seconds. <br /> If your browser does not automatically return, <br />please click [<a href=".$url." target=_self> Here </a>] Enter .";
			//$html .="<br><br> [<a href='#' onclick='history.go(-1)'> Back </a>]";
			$html .="<br><br></td></tr></table></td></tr></table>";
			$html .="</body></html>";
			echo $html;
		}
		exit;
	}
	
	/*
		include("function.php");
		$total=mysql_num_rows($result);
		pageft($total,10);
		$result=mysql_query("select * from wp_shoutlugmap order by id desc limit $firstcount,$displaypg");
		while($row=mysql_fetch_array($result)){
			// display something
		}
		echo $pagenav;
	*/
	
	function pageft($totle,$displaypg=20,$url=''){
		global $page,$firstcount,$pagenav,$_SERVER;
		$GLOBALS["displaypg"]=$displaypg;
		if(!$page){$page=1;}
		if(!$url){$url=$_SERVER["REQUEST_URI"];}
		
		$parse_url=parse_url($url);
		$url_query=$parse_url["query"]; 
		if($url_query){
			$url_query=ereg_replace("(^|&)page=$page","",$url_query);
			$url=str_replace($parse_url["query"],$url_query,$url);
			if($url_query){$url.="&page";}else{$url.="page";}
		}else {
			$url.="?page";
		}
		
		$lastpg=ceil($totle/$displaypg);
		$page=min($lastpg,$page);
		$prepg=$page-1;
		$nextpg=($page==$lastpg ? 0 : $page+1); 
		$firstcount=($page-1)*$displaypg;
		
		$pagenav="显示第 <B>".($totle?($firstcount+1):0)."</B>-<B>".min($firstcount+$displaypg,$totle)."</B> 条记录,共 $totle 条记录<BR>";
		
		if($lastpg<=1){return false;}
		
		$pagenav.=" <a href='$url=1'>首页</a> ";
		if($prepg){$pagenav.=" <a href='$url=$prepg'>前页</a> ";}else{$pagenav.=" 前页 ";}
		if($nextpg){$pagenav.=" <a href='$url=$nextpg'>后页</a> ";}else{$pagenav.=" 后页 ";}
		$pagenav.=" <a href='$url=$lastpg'>尾页</a> ";
		
		$pagenav.=" 到第 <select name='topage' size='1' onchange='window.location=\"$url=\"+this.value'>\n";
		for($i=1;$i<=$lastpg;$i++){
			if($i==$page){
				$pagenav.="<option value='$i' selected>$i</option>\n";
			}else{
				$pagenav.="<option value='$i'>$i</option>\n";
			}
		}
		$pagenav.="</select> 页,共 $lastpg 页";
	}

	// 产生随机字符串函数
	function random($length) {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		mt_srand((double)microtime() * 1000000);
		for($i = 0; $i < $length; $i++) {
		  $hash .= $chars[mt_rand(0, $max)];
		}
		return $hash;
	}
	
	// 获得文件后缀
	function extend($file_name){
		$extend = pathinfo($file_name);
		$extend = strtolower($extend["extension"]);
		return $extend;
	}

	// 该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。
	function makeLinks($text) {
		$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)','<a href="\1">\1</a>', $text);
		$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)','\1<a href="http://\2">\2</a>', $text);
		$text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})','<a href="mailto:\1">\1</a>', $text);  

		return $text;
	}

	// 随着 WordPress 越来越普及,Gravatar 也随之流行。由于 Gravatar 提供了易于使用的API,将其纳入应用程序也变得十分方便。
	/******************
	*@email - Email address to show gravatar for
	*@size - size of gravatar
	*@default - URL of default gravatar to use
	*@rating - rating of Gravatar(G, PG, R, X)
	*/
	function show_gravatar($email, $size, $default, $rating)
	{
		echo '<img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).
			'&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px"
			height="'.$size.'px" />';
	}

	// 创建标签云
	function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
	{
		$minimumCount = min( array_values( $data ) );
		$maximumCount = max( array_values( $data ) );
		$spread       = $maximumCount - $minimumCount;
		$cloudHTML    = '';
		$cloudTags    = array();  

		$spread == 0 && $spread = 1;  

		foreach( $data as $tag => $count )
		{
			$size = $minFontSize + ( $count - $minimumCount )
				* ( $maxFontSize - $minFontSize ) / $spread;
			$cloudTags[] = '<a style="font-size: ' . floor( $size ) . 'px'
			. '" href="#" title="\'' . $tag  .
			'\' returned a count of ' . $count . '">'
			. htmlspecialchars( stripslashes( $tag ) ) . '</a>';
		}  

		return join( "\n", $cloudTags ) . "\n";
	}
	/**************************
	****   Sample usage    ***/
	/*
	$arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43,
		'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42,
		'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30,
		'Extract' => 28, 'Filters' => 42);

	echo getCloud($arr, 12, 36);
	*/

	// 为用户提供强制性的文件下载功能。
	/********************
	*@file - path to file
	* eg: force_download('10.png');
	*/
	function force_download($file)
	{
		if ((isset($file))&&(file_exists($file))) {
		   header("Content-length: ".filesize($file));
		   header('Content-Type: application/octet-stream');
		   header('Content-Disposition: attachment; filename="' . $file . '"');
		   readfile("$file");
		} else {
		   echo "No file selected";
		}
	}

	// 建用户友好的日志缩略名。
	function create_slug($string){
		$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
		return $slug;
	}


/****************************************************************************************
* $dir_name = 'message/templates';  //返回哪个目录的总文件数                               *
* $file_count = get_file_count($dir_name);                                              *
* echo $dir_name.'目录下文件总数:<font color="red">'.count($file_count).'</font><br />';  *
* print_r($file_count); 																*
*****************************************************************************************/
	
	function get_file_count($dir_name){               //得到目录下的文件函数
	  global $files;                                 //申明全局变量有于统计
	  $od = opendir($dir_name);                      //打开目录,返回连接号
	  while ($name = readdir($od)){                    //读取目录
		$file_path = $dir_name.'/'.$name;            //目录 用于使用 is_file()
		if (is_file($file_path)){                     //是一个文件
			$files[] = $file_path;                     //添加,用于最后的统计
		}elseif (($name !='.') && ($name !='..')){    //输出$name看看就知道
			get_file_count($file_path);              //递归的调用
		}
	  }
	  return $files;                          //返回目录下的总文件数
	}
	
	//
	// Function: 获取远程图片并把它保存到本地
	//
	// 确定您有把文件写入本地服务器的权限
	//
	// 变量说明:
	// $url 是远程图片的完整URL地址,不能为空。
	// $filename 是可选变量: 如果为空,本地文件名将基于时间和日期
	// 自动生成.

	function GrabImage($url,$filename='') {
		if($url == ''){return false;}
		if($filename == '') {
			$ext = strrchr($url,'.');
			if($ext != '.gif' && $ext != '.jpg'){return false;}
			$filename = date('dMYHis').$ext;
		}
		ob_start();
		readfile($url);
		$img = ob_get_contents();
		ob_end_clean();
		$size = strlen($img);
		$fp2 = @fopen($filename, 'a');
		fwrite($fp2,$img);
		fclose($fp2);
		return $filename;
	}

/*
	$img = GrabImage('http://dl.iteye.com/upload/picture/pic/55053/2d4fa08f-4e39-3ca2-8087-fc2fd1c836ec.jpg','');
	if($img){
		echo '<pre><img src="'.$img.'"></pre>';
	}else{
		echo 'false';
	}
*/


/* 计算复活节 echo easter(); 默认为今年 */

	function easter($year = ''){
		return empty($year) ? date("m-d-Y", easter_date()) : date("m-d-Y", easter_date($year)); 
	}

/***********************************************
	求相对路径
	$path_a = "/mytest/jquery.js";
	$path_b = "/willdo/church/index.php";
	echo compara_path($path_a, $path_b);
************************************************/

	function compara_path($path_a, $path_b) {
		//切割路径.
		$array_a = explode('/', $path_a);
		$array_b = explode('/', $path_b);
	
		//从数组中删除最后的文件,剩下的全为文件夹名称.
		$file_a = array_pop($array_a);
		$file_b = array_pop($array_b);
	
		//子目录个数.
		$a_len = count($array_a);
		$b_len = count($array_b);
	
		//循环求出第几个目录不同.
		for ( $i = 0; $i < $a_len; $i++ ) {
			if ($array_a[$i] != $array_b[$i] ) {
				break;
			}
		}
	
		//求出相对路径.
		$com_path = '';
		for ( $j = 0; $j < $a_len - $i; $j++ ) {
			$com_path .= '../';
		}
	
		for ( $i; $i< $b_len; $i++ ) {
			$com_path .= $array_b[$i] . '/';
		}
	
		$com_path .= $file_b;
		return $com_path;
	}
	
?>
 

 

你可能感兴趣的:(JavaScript,html,mysql,css,ext)