搜索
首页后端开发php教程PHP效能集合类源码

PHP效能集合类源码

Jun 13, 2016 am 11:45 AM
filefunctionparamreturnstring

PHP功能集合类源码

代码如下:

<?php/**  * 常用工具类  * author Lee.  艾妮 http://ini.iteye.com* Last modify $Date: 2012-8-23*/class Tool {	/**	 * js 弹窗并且跳转	 * @param string $_info	 * @param string $_url	 * @return js	 */	static public function alertLocation($_info, $_url) {		echo "<script type='text/javascript'>alert('$_info');location.href='$_url';</script>";		exit();	}		/**	 * js 弹窗返回	 * @param string $_info	 * @return js	 */	static public function alertBack($_info) {		echo "<script type='text/javascript'>alert('$_info');history.back();</script>";		exit();	}		/**	 * 页面跳转	 * @param string $url	 * @return js	 */	static public function headerUrl($url) {		echo "<script type='text/javascript'>location.href='{$url}';</script>";		exit();	}		/**	 * 弹窗关闭	 * @param string $_info	 * @return js	 */	static public function alertClose($_info) {		echo "<script type='text/javascript'>alert('$_info');close();</script>";		exit();	}		/**	 * 弹窗	 * @param string $_info	 * @return js	 */	static public function alert($_info) {		echo "<script type='text/javascript'>alert('$_info');</script>";		exit();	}		/**	 * 系统基本参数上传图片专用	 * @param string $_path	 * @return null	 */	static public function sysUploadImg($_path) {		echo '<script type="text/javascript">document.getElementById("logo").value="'.$_path.'";</script>';		echo '<script type="text/javascript">document.getElementById("pic").src="'.$_path.'";</script>';		echo '<script type="text/javascript">$("#loginpop1").hide();</script>';		echo '<script type="text/javascript">$("#bgloginpop2").hide();</script>';	}		/**	 * html过滤	 * @param array|object $_date	 * @return string	 */	static public function htmlString($_date) {		if (is_array($_date)) {			foreach ($_date as $_key=>$_value) {				$_string[$_key] = Tool::htmlString($_value);  //递归			}		} elseif (is_object($_date)) {			foreach ($_date as $_key=>$_value) {				$_string->$_key = Tool::htmlString($_value);  //递归			}		} else {			$_string = htmlspecialchars($_date);		}		return $_string;	}		/**	 * 数据库输入过滤	 * @param string $_data	 * @return string	 */	static public function mysqlString($_data) {		$_data = trim($_data);		return !GPC ? addcslashes($_data) : $_data;	}		/**	 * 清理session	 */	static public function unSession() {		if (session_start()) {			session_destroy();		}	}		/**	 * 验证是否为空	 * @param string $str	 * @param string $name	 * @return bool (true or false)	 */	static function validateEmpty($str, $name) {		if (empty($str)) {			self::alertBack('警告:' .$name . '不能为空!');		}	}		/**	 * 验证是否相同	 * @param string $str1	 * @param string $str2	 * @param string $alert	 * @return JS 	 */	static function validateAll($str1, $str2, $alert) {		if ($str1 != $str2) self::alertBack('警告:' .$alert);	}		/**	 * 验证ID	 * @param Number $id	 * @return JS	 */	static function validateId($id) {		if (empty($id) || !is_numeric($id)) self::alertBack('警告:参数错误!');	}		/**	 * 格式化字符串	 * @param string $str	 * @return string	 */	static public function formatStr($str) {		$arr = array(' ', '	', '&', '@', '#', '%',  '\'', '"', '\\', '/', '.', ',', '$', '^', '*', '(', ')', '[', ']', '{', '}', '|', '~', '`', '?', '!', ';', ':', '-', '_', '+', '=');		foreach ($arr as $v) {			$str = str_replace($v, '', $str);		}		return $str;	}		/**	 * 格式化时间	 * @param int $time 时间戳	 * @return string	 */	static public function formatDate($time='default') {		$date = $time == 'default' ? date('Y-m-d H:i:s', time()) : date('Y-m-d H:i:s', $time);		return $date;	}		/**  	* 获得真实IP地址  	* @return string  	*/	static public 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;  	}		/**	 * 加载 Smarty 模板	 * @param string $html	 * @return null;	 */	static public function display() {		global $tpl;$html = null;		$htmlArr = explode('/', $_SERVER[SCRIPT_NAME]);		$html = str_ireplace('.php', '.html', $htmlArr[count($htmlArr)-1]);		$dir = dirname($_SERVER[SCRIPT_NAME]);		$firstStr = substr($dir, 0, 1);		$endStr = substr($dir, strlen($dir)-1, 1);		if ($firstStr == '/' || $firstStr == '\\') $dir = substr($dir, 1);		if ($endStr != '/' || $endStr != '\\') $dir = $dir . '/';		$tpl->display($dir.$html);	}		/**	 * 创建目录	 * @param string $dir	 */	static public function createDir($dir) {		if (!is_dir($dir)) {			mkdir($dir, 0777);		}	}		/**	 * 创建文件(默认为空)	 * @param unknown_type $filename	 */	static public function createFile($filename) {		if (!is_file($filename)) touch($filename);	}		/**	 * 正确获取变量	 * @param string $param	 * @param string $type	 * @return string	 */	static public function getData($param, $type='post') {		$type = strtolower($type);		if ($type=='post') {			return Tool::mysqlString(trim($_POST[$param]));		} elseif ($type=='get') {			return Tool::mysqlString(trim($_GET[$param]));		}	}		/**	 * 删除文件	 * @param string $filename	 */	static public function delFile($filename) {		if (file_exists($filename)) unlink($filename);	}		/**	 * 删除目录	 * @param string $path	 */	static public function delDir($path) {		if (is_dir($path)) rmdir($path);	}		/**	 * 删除目录及地下的全部文件	 * @param string $dir	 * @return bool	 */	static public function delDirOfAll($dir) {		//先删除目录下的文件:		if (is_dir($dir)) {			$dh=opendir($dir);			while (!!$file=readdir($dh)) {				if($file!="." && $file!="..") {					$fullpath=$dir."/".$file;					if(!is_dir($fullpath)) {						unlink($fullpath);					} else {						self::delDirOfAll($fullpath);					}				}			}			closedir($dh);			//删除当前文件夹:			if(rmdir($dir)) {		    	return true;			} else {				return false;			}		}	}	/**	 * 验证登陆	 */	static public function validateLogin() {		if (empty($_SESSION['admin']['user'])) header('Location:/admin/');	}		/**	 * 给已经存在的图片添加水印	 * @param string $file_path	 * @return bool	 */	static public function addMark($file_path) {		if (file_exists($file_path) && file_exists(MARK)) {			//求出上传图片的名称后缀			$ext_name = strtolower(substr($file_path, strrpos($file_path, '.'), strlen($file_path)));			//$new_name='jzy_' . time() . rand(1000,9999) . $ext_name ;			$store_path = ROOT_PATH . UPDIR;			//求上传图片高宽			$imginfo = getimagesize($file_path);			$width = $imginfo[0];			$height = $imginfo[1];			 //添加图片水印             			switch($ext_name) {				case '.gif':					$dst_im = imagecreatefromgif($file_path);					break;				case '.jpg':					$dst_im = imagecreatefromjpeg($file_path);					break;				case '.png':					$dst_im = imagecreatefrompng($file_path);					break;			}			$src_im = imagecreatefrompng(MARK);			//求水印图片高宽			$src_imginfo = getimagesize(MARK);			$src_width = $src_imginfo[0];			$src_height = $src_imginfo[1];			//求出水印图片的实际生成位置			$src_x = $width - $src_width - 10;			$src_y = $height - $src_height - 10;			//新建一个真彩色图像			$nimage = imagecreatetruecolor($width, $height);               			//拷贝上传图片到真彩图像			imagecopy($nimage, $dst_im, 0, 0, 0, 0, $width, $height);          			//按坐标位置拷贝水印图片到真彩图像上			imagecopy($nimage, $src_im, $src_x, $src_y, 0, 0, $src_width, $src_height);			//分情况输出生成后的水印图片			switch($ext_name) {				case '.gif':					imagegif($nimage, $file_path);					break;				case '.jpg':					imagejpeg($nimage, $file_path);					break;				case '.png':					imagepng($nimage, $file_path);					break;     			}			//释放资源 			imagedestroy($dst_im);			imagedestroy($src_im);			unset($imginfo);			unset($src_imginfo);			//移动生成后的图片			@move_uploaded_file($file_path, ROOT_PATH.UPDIR . $file_path);		}	}		/**	*  中文截取2,单字节截取模式	* @access public	* @param string $str  需要截取的字符串	* @param int $slen  截取的长度	* @param int $startdd  开始标记处	* @return string	*/	static public function cn_substr($str, $slen, $startdd=0){		$cfg_soft_lang = PAGECHARSET;		if($cfg_soft_lang=='utf-8') {			return self::cn_substr_utf8($str, $slen, $startdd);		}		$restr = '';		$c = '';		$str_len = strlen($str);		if($str_len < $startdd+1) {			return '';		}		if($str_len < $startdd + $slen || $slen==0) {			$slen = $str_len - $startdd;		}		$enddd = $startdd + $slen - 1;		for($i=0;$i<$str_len;$i++) {			if($startdd==0) {				$restr .= $c;			} elseif($i > $startdd) {				$restr .= $c;			}			if(ord($str[$i])>0x80) {				if($str_len>$i+1) {					$c = $str[$i].$str[$i+1];				}				$i++;			} else {				$c = $str[$i];			}			if($i >= $enddd) {				if(strlen($restr)+strlen($c)>$slen) {					break;				} else {					$restr .= $c;					break;				}			}		}		return $restr;	}	/**	*  utf-8中文截取,单字节截取模式	*	* @access public	* @param string $str 需要截取的字符串	* @param int $slen 截取的长度	* @param int $startdd 开始标记处	* @return string	*/	static public function cn_substr_utf8($str, $length, $start=0) {		if(strlen($str) < $start+1) {			return '';		}		preg_match_all("/./su", $str, $ar);		$str = '';		$tstr = '';		//为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取		for($i=0; isset($ar[0][$i]); $i++) {			if(strlen($tstr) < $start) {				$tstr .= $ar[0][$i];			} else {				if(strlen($str) < $length + strlen($ar[0][$i]) ) {					$str .= $ar[0][$i];				} else {					break;				}			}		}		return $str;	}		/**	 * 删除图片,根据图片ID	 * @param int $image_id	 */	static function delPicByImageId($image_id) {		$db_name = PREFIX . 'images i';		$m = new Model();		$data = $m->getOne($db_name, "i.id={$image_id}", "i.path as p, i.big_img as b, i.small_img as s");		foreach ($data as $v) {			@self::delFile(ROOT_PATH . $v['p']);			@self::delFile(ROOT_PATH . $v['b']);			@self::delFile(ROOT_PATH . $v['s']);		}		$m->del(PREFIX . 'images', "id={$image_id}");		unset($m);	}		/**	 * 图片等比例缩放	 * @param resource $im    新建图片资源(imagecreatefromjpeg/imagecreatefrompng/imagecreatefromgif)	 * @param int $maxwidth   生成图像宽	 * @param int $maxheight  生成图像高	 * @param string $name    生成图像名称	 * @param string $filetype文件类型(.jpg/.gif/.png)	 */	static public function resizeImage($im, $maxwidth, $maxheight, $name, $filetype) {		$pic_width = imagesx($im);		$pic_height = imagesy($im);		if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {			if($maxwidth && $pic_width>$maxwidth) {				$widthratio = $maxwidth/$pic_width;				$resizewidth_tag = true;			}			if($maxheight && $pic_height>$maxheight) {				$heightratio = $maxheight/$pic_height;				$resizeheight_tag = true;			}			if($resizewidth_tag && $resizeheight_tag) {				if($widthratio<$heightratio)					$ratio = $widthratio;				else					$ratio = $heightratio;			}			if($resizewidth_tag && !$resizeheight_tag)				$ratio = $widthratio;			if($resizeheight_tag && !$resizewidth_tag)				$ratio = $heightratio;			$newwidth = $pic_width * $ratio;			$newheight = $pic_height * $ratio;			if(function_exists("imagecopyresampled")) {				$newim = imagecreatetruecolor($newwidth,$newheight);				imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);			} else {				$newim = imagecreate($newwidth,$newheight);				imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);			}			$name = $name.$filetype;			imagejpeg($newim,$name);			imagedestroy($newim);		} else {			$name = $name.$filetype;			imagejpeg($im,$name);		}	}	/**	 * 下载文件	 * @param string $file_path 绝对路径	 */	static public function downFile($file_path) {		//判断文件是否存在		$file_path = iconv('utf-8', 'gb2312', $file_path); //对可能出现的中文名称进行转码		if (!file_exists($file_path)) {			exit('文件不存在!');		}		$file_name = basename($file_path); //获取文件名称		$file_size = filesize($file_path); //获取文件大小		$fp = fopen($file_path, 'r'); //以只读的方式打开文件		header("Content-type: application/octet-stream");		header("Accept-Ranges: bytes");		header("Accept-Length: {$file_size}");		header("Content-Disposition: attachment;filename={$file_name}");		$buffer = 1024;		$file_count = 0;		//判断文件是否结束		while (!feof($fp) && ($file_size-$file_count>0)) {			$file_data = fread($fp, $buffer);			$file_count += $buffer;			echo $file_data;		}		fclose($fp); //关闭文件	}}?>

?

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
PHP与Python:了解差异PHP与Python:了解差异Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

php:死亡还是简单地适应?php:死亡还是简单地适应?Apr 11, 2025 am 12:13 AM

PHP不是在消亡,而是在不断适应和进化。1)PHP从1994年起经历多次版本迭代,适应新技术趋势。2)目前广泛应用于电子商务、内容管理系统等领域。3)PHP8引入JIT编译器等功能,提升性能和现代化。4)使用OPcache和遵循PSR-12标准可优化性能和代码质量。

PHP的未来:改编和创新PHP的未来:改编和创新Apr 11, 2025 am 12:01 AM

PHP的未来将通过适应新技术趋势和引入创新特性来实现:1)适应云计算、容器化和微服务架构,支持Docker和Kubernetes;2)引入JIT编译器和枚举类型,提升性能和数据处理效率;3)持续优化性能和推广最佳实践。

您什么时候使用特质与PHP中的抽象类或接口?您什么时候使用特质与PHP中的抽象类或接口?Apr 10, 2025 am 09:39 AM

在PHP中,trait适用于需要方法复用但不适合使用继承的情况。1)trait允许在类中复用方法,避免多重继承复杂性。2)使用trait时需注意方法冲突,可通过insteadof和as关键字解决。3)应避免过度使用trait,保持其单一职责,以优化性能和提高代码可维护性。

什么是依赖性注入容器(DIC),为什么在PHP中使用一个?什么是依赖性注入容器(DIC),为什么在PHP中使用一个?Apr 10, 2025 am 09:38 AM

依赖注入容器(DIC)是一种管理和提供对象依赖关系的工具,用于PHP项目中。DIC的主要好处包括:1.解耦,使组件独立,代码易维护和测试;2.灵活性,易替换或修改依赖关系;3.可测试性,方便注入mock对象进行单元测试。

与常规PHP阵列相比,解释SPL SplfixedArray及其性能特征。与常规PHP阵列相比,解释SPL SplfixedArray及其性能特征。Apr 10, 2025 am 09:37 AM

SplFixedArray在PHP中是一种固定大小的数组,适用于需要高性能和低内存使用量的场景。1)它在创建时需指定大小,避免动态调整带来的开销。2)基于C语言数组,直接操作内存,访问速度快。3)适合大规模数据处理和内存敏感环境,但需谨慎使用,因其大小固定。

PHP如何安全地上载文件?PHP如何安全地上载文件?Apr 10, 2025 am 09:37 AM

PHP通过$\_FILES变量处理文件上传,确保安全性的方法包括:1.检查上传错误,2.验证文件类型和大小,3.防止文件覆盖,4.移动文件到永久存储位置。

什么是无效的合并操作员(??)和无效分配运算符(?? =)?什么是无效的合并操作员(??)和无效分配运算符(?? =)?Apr 10, 2025 am 09:33 AM

JavaScript中处理空值可以使用NullCoalescingOperator(??)和NullCoalescingAssignmentOperator(??=)。1.??返回第一个非null或非undefined的操作数。2.??=将变量赋值为右操作数的值,但前提是该变量为null或undefined。这些操作符简化了代码逻辑,提高了可读性和性能。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境