PHP 函数库

1、关于 URL

<?php
/*
* 返回页面的当前完整路径,包括参数
*/
function currentUrl() {
	$url = 'http';
	if ($_SERVER["HTTPS"] == "on") $url .= "s";
	$url .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
		$url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
	} else {
		$url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
	}
	return $url;
}

/*
* 返回页面的当前完整路径,不包括参数
*/
function curUrlNoArgs() {
	$url = 'http';
	if ($_SERVER["HTTPS"] == "on") $url .= "s";
	$url .= "://";
	$this_page = $_SERVER["REQUEST_URI"];
	# 不获取?后面的参数
	if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
	if ($_SERVER["SERVER_PORT"] != "80") {
		$url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $this_page;
	} else {
		$url .= $_SERVER["SERVER_NAME"] . $this_page;
	}
	return $url;
}

/*
* $_SERVER['REQUEST_URI'] 的通用解决方案,防止 rewrite 规则可能出现错误
*/ 
function requestURI() {
	if (isset($_SERVER['REQUEST_URI'])){
		$uri = $_SERVER['REQUEST_URI'];
	} else {
		if (isset($_SERVER['argv'])) {
			$uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['argv'][0];
		} else {
			$uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
		}
	}
	return $uri;
}

?>

2、数据入库前格式化数据,防止 SQL 注入

<?php
/*
* 数据入库之前格式化数据(防止 SQL 注入)
*/
function site_addslashes($string, $force = 0) { 
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force);
			}
		} else {
			$string = addslashes($string); 
		}
	}
	return $string;
}
?>

3、PHP 生成 唯一标识符码
<?php
/*
* 唯一标识符
*/
function create_unique() {
	$data = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'] .time() . rand();
	return sha1($data);
}
?> 

4、PHP表单验证类 validator.class.php

<?php
#验证类
class validator { 
	/** 
	* 验证邮箱
	* @param string $string 
	* @param bool $required 
	* @return bool 
	*/ 
	public static function isEmail ($string, $required = false) { 
		$isRightFormat = false;
		if($string == '' && $required ===false) $isRightFormat = true;
		$exp_match = '/([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/';
		$isRightFormat = preg_match($exp_match, $string) ? true : false;
		return $isRightFormat;
	}

	/** 
	* 验证 URL
	* @param string $string 
	* @param bool $required 
	* @return bool 
	*/ 
	public static function isHttpUrl ($string, $required =false) { 
		$isRightFormat = false;
		if($string =='' && $required ===false) $isRightFormat = true; 
		$exp_match = '/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/';
		$isRightFormat = preg_math($exp_match, $string) ? true : false;
		return $isRightFormat;
	}
	/** 
	* 验证手机
	* @param string $string 
	* @param bool $required 
	* @return bool 
	*/ 
	public static function isCellPhone ($string, $required = false) { 
		$isRightFormat = false; 
		if($string == '' && $required ===false) $isRightFormat = true; 
		$exp_match = '/^((\(\d{3}\))|(\d{3}\-))?1[3,5]\d{9}$/';
		$isRightFormat = preg_match($exp_match, $string) ? true : false;
		return $isRightFormat;
	} 
	/** 
	* 验证电话号码
	* @param string $string 
	* @param bool $required 
	* @return bool 
	*/ 
	public static function isPhone ($string, $required = false) { 
		$isRightFormat = false; 
		if($string == "" && $required === false) $isRightFormat = true; 
		$exp_match = '/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/';
		$isRightFormat = preg_match($exp_match, $string) ? true : false;
		return $isRightFormat;
	} 
	/** 
	* 验证邮编
	* @param string $string
	* @param bool $required
	* @return bool
	*/
	public static function isZipCode ($string, $required =false) {
		$isRightFormat = false;
		if($string == '' && $required ===false) $isRightFormat = true;
		$exp_match = '/[0-9]{6}/';
		$isRightFormat = preg_match($exp_match, $string) ? true : false;
		return $isRightFormat;
	}
	/** 
	* 验证日期(2011-12-30)
	* @param string $string 
	* @param bool $required 
	* @return bool 
	*/ 
	public static function isDateFormat ($string, $required = false) {
		$isRightFormat = false; 
		if($string == '' && $required === false) $isRightFormat = true; 
		$exp_match = '/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/';
		if(preg_match($exp_match, $string)) {
			$dateArray = explode('-', $string);
			$isRightFormat = checkdate($dateArray[1], $dateArray[2], $dateArray[0]) ? true : false; 
		}
		return $isRightFormat;
	} 
	/** 
	* 验证金钱
	* @param string $string 
	* @param bool $required 
	* @return bool 
	*/ 
	public static function isMoney ($string, $required = false) { 
		$isRightFormat = true; 
		if($string == '' && $required === false) $isRightFormat = true;
		$exp_match = '/^[0-9]{1,8}[.]{0,1}[0-9]{0,2}$/'; 
		$isRightFormat = preg_match($exp_match, $string) ? true : false; 
		return $isRightFormat; 
	}

} 

?>

5、去掉指定的 HTML 标签

<?php
/**  
* 去掉指定的html标签
* @param array $string  
* @param bool $str 
* @return string
*/
function _strip_tags($tagsArr,$str) { 
    foreach ($tagsArr as $tag) {
        $p[]="/(<(?:\/".$tag."|".$tag.")[^>]*>)/i";
    }
    $return_str = preg_replace($p,"",$str);
    return $return_str;
}

$str = "<b>您好</b><input type='text' name='' />";
_strip_tags(array("b","input"),$str); #去掉 B 标签和 INPUT 标签
?>

6、便利文件夹文件

<?php
/* 
* 遍历文件夹文件,返回数组
* @return array
*/ 
function list_files($folder = '', $levels = 100 ) { 
	if(empty($folder)) return false;
	if(!$levels ) return false;
	$files = array();
	if ($dir = @opendir($folder)) {
		while (($file = readdir($dir))!==false) {
			if (in_array($file, array('.', '..')))
				continue;
			if (is_dir( $folder . '/' . $file )){
				$files2 = list_files( $folder . '/' . $file, $levels - 1); 
				if( $files2 ) { 
					$files = array_merge($files, $files2 ); 
				} else {
					$files[] = $folder . '/' . $file . '/';
				}
			} else {
				$files[] = $folder . '/' . $file;
			}
		}
	}
	@closedir($dir); 
	return $files; 
}

print_r(list_files('phpmyadmin')); # 打印 phpmyadmin 下所有目录和文件
?> 

7、返回文件类型

<?php
/* 
* 返回文件类型 
* @param string $filename 文件路径
* @return array 返回数组,键值分别为:ext、type
*/ 
function getFileType($filename) {
    $mimes = array( 
		'jpg|jpeg|jpe' => 'image/jpeg', 
		'gif' => 'image/gif', 
		'png' => 'image/png', 
		'bmp' => 'image/bmp', 
		'tif|tiff' => 'image/tiff', 
		'ico' => 'image/x-icon', 
		'asf|asx|wax|wmv|wmx' => 'video/asf', 
		'avi' => 'video/avi', 
		'divx' => 'video/divx', 
		'mov|qt' => 'video/quicktime', 
		'mpeg|mpg|mpe|mp4' => 'video/mpeg', 
		'txt|c|cc|h' => 'text/plain', 
		'rtx' => 'text/richtext', 
		'css' => 'text/css', 
		'htm|html' => 'text/html', 
		'mp3|m4a' => 'audio/mpeg', 
		'ra|ram' => 'audio/x-realaudio', 
		'wav' => 'audio/wav', 
		'ogg' => 'audio/ogg', 
		'mid|midi' => 'audio/midi', 
		'wma' => 'audio/wma', 
		'rtf' => 'application/rtf', 
		'js' => 'application/javascript', 
		'pdf' => 'application/pdf', 
		'doc|docx' => 'application/msword', 
		'pot|pps|ppt|pptx' => 'application/vnd.ms-powerpoint', 
		'wri' => 'application/vnd.ms-write', 
		'xla|xls|xlsx|xlt|xlw' => 'application/vnd.ms-excel', 
		'mdb' => 'application/vnd.ms-access', 
		'mpp' => 'application/vnd.ms-project', 
		'swf' => 'application/x-shockwave-flash', 
		'class' => 'application/java', 
		'tar' => 'application/x-tar', 
		'zip' => 'application/zip', 
		'gz|gzip' => 'application/x-gzip', 
		'exe' => 'application/x-msdownload', 
		'odt' => 'application/vnd.oasis.opendocument.text', 
		'odp' => 'application/vnd.oasis.opendocument.presentation', 
		'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 
		'odg' => 'application/vnd.oasis.opendocument.graphics', 
		'odc' => 'application/vnd.oasis.opendocument.chart', 
		'odb' => 'application/vnd.oasis.opendocument.database', 
		'odf' => 'application/vnd.oasis.opendocument.formula'
    );
	$type = false;
	$ext = false;
	foreach ( $mimes as $ext_preg => $mime_match ) {
		$ext_preg = '!\.(' . $ext_preg . ')$!i';
		if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
			$type = $mime_match;
			$ext = $ext_matches[1];
			break;
		}
	}
    return compact('ext','type'); 
}
print_r(getFileType('123.jpg')); #Array ( [ext] => jpg [type] => image/jpeg )
?> 

8、获取用户真实 IP

<?php
/** 
* 获得真实IP地址 
* @return string 
*/ 
function realIp() { 
	static $realip = NULL; 
	if ($realip !== NULL) return $realip;
	if (isset($_SERVER)) {
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			foreach ($arr AS $ip) {
				$ip = trim($ip);
				if ($ip != 'unknown') { 
					$realip = $ip; 
					break; 
				} 
			} 
		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { 
			$realip = $_SERVER['HTTP_CLIENT_IP'];
		} else { 
			if (isset($_SERVER['REMOTE_ADDR'])) { 
				$realip = $_SERVER['REMOTE_ADDR']; 
			} else { 
				$realip = '0.0.0.0'; 
			}
		}
	} else {
		if (getenv('HTTP_X_FORWARDED_FOR')) {
			$realip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('HTTP_CLIENT_IP')) {
			$realip = getenv('HTTP_CLIENT_IP');
		} else {
			$realip = getenv('REMOTE_ADDR');
		}
	}
	preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
	$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
	return $realip;
}
?>

9、下载远程图片

<?php  
/** 
 * 下载远程 HTTP 图片 
 * @param string $url 远程图片地址 
 * @param string $filename 下载后的图片名称,默认为空 
 * @param string $dir 保存图片目录 
 */  
function downHttpImage($url, $filename="", $dir) {   
	if($url=="") return false;  
	if($filename=="") {  
		$ext=strtolower(strrchr($url,"."));  
		if($ext!=".gif" && $ext!=".jpg" && $ext!=".png" && $ext!=".bmp") {  
			return false;  
		} else {  
			$filename=sha1(rand(1,100000)).$ext;   
		}  
	}  
	ob_start();  
	readfile($url);  
	$img = ob_get_contents();  
	ob_end_clean();  
	$size = strlen($img);  
	$filename = $dir . $filename;  
	$fp2=@fopen($filename, "a");  
	fwrite($fp2, $img);  
	fclose($fp2);  
	return $filename;  
}  
downHttpImage("http://imgsrc.baidu.com/baike/abpic/item/3c6d55fbb2fb4316214fa43f20a4462309f7d327.jpg", '', 'images/');  
?>

10、判断字符串中是否有中文

<?php
/**
* 判断字符串中是否有中文
* @param string $str
* @return bool
*/
function isChinese($str) {
	return preg_match("/[\x80-\xff]./", $str);
}
?>

11、处理图片

/**
 * 输出缩略图
 * @param string $filename 图片地址
 * @param int $width 图片宽度
 * @param int $height图片高度
 */
function handleImg($filename,$width='500',$height='500'){
    $picext = end(explode('.',$filename));
    $picexts = array('jpg','png','gif','jpeg');
    if(in_array($picext,$picexts)) {
        if($picext=='jpg' || $picext=='jpeg') {
            header('Content-type: image/jpeg');
        } else {
            header('Content-type: image/'.$picext);
        }
        list($owidth, $oheight) = getimagesize($filename);
        $thumb = imagecreatetruecolor($width, $height);
        if($picext=='jpg' || $picext=='jpeg'){
            $source = imagecreatefromjpeg($filename);
            imagecopyresized($thumb, $source, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
            imagejpeg($thumb);
        } elseif ($picext=='gif') {
            $source = imagecreatefromgif($filename);
            imagecopyresized($thumb, $source, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
            imagegif($thumb);
        } elseif ($picext=='png'){
            $source = imagecreatefrompng($filename);
            imagecopyresized($thumb, $source, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
            imagepng($thumb);
        }
    } else {
        echo 'the file is not image!';
    }
}
handleImg('bjdt.jpg','300','200');

12、关于 date

/**
 * 获取日期段的全部日期集合
 * @param string $sdate
 * @param string $edate
 * @return array
 */
function datesParag($sdate, $edate) {
    $dates = array();
    $dt_start = strtotime($sdate);
    $dt_end   = strtotime($edate);
    do { 
        array_push($dates, date('Y-m-d', $dt_start));
    } while (($dt_start += 86400) <= $dt_end);
    return $dates;
}
datesParag('2013-09-10', '2013-09-20');


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值