백엔드 개발 PHP 튜토리얼 PHP效能集合类源码

PHP效能集合类源码

Jun 13, 2016 am 11:45 AM
file function param return string

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으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Hongmeng 네이티브 애플리케이션 무작위 시 Hongmeng 네이티브 애플리케이션 무작위 시 Feb 19, 2024 pm 01:36 PM

오픈 소스에 대해 자세히 알아보려면 다음을 방문하세요. 51CTO Hongmeng 개발자 커뮤니티 https://ost.51cto.com 실행 환경 DAYU200:4.0.10.16SDK: 4.0.10.15IDE: 4.0.600 1. 애플리케이션을 생성하려면 파일을 클릭합니다. >새파일->CreateProgect. 템플릿 선택: [OpenHarmony]EmptyAbility: 프로젝트 이름 shici, 애플리케이션 패키지 이름 com.nut.shici 및 애플리케이션 저장 위치 XXX(한자, 특수 문자, 공백 없음)를 입력합니다. CompileSDK10, 모델: 스테이지. 장치

Java의 File.length() 함수를 사용하여 파일 크기를 가져옵니다. Java의 File.length() 함수를 사용하여 파일 크기를 가져옵니다. Jul 24, 2023 am 08:36 AM

파일 크기를 얻으려면 Java의 File.length() 함수를 사용하십시오. 파일 크기는 파일 작업을 처리할 때 매우 일반적인 요구 사항입니다. Java는 파일 크기를 얻는 매우 편리한 방법, 즉 길이( ) File 클래스의 메서드입니다. 이 기사에서는 이 방법을 사용하여 파일 크기를 가져오는 방법을 소개하고 해당 코드 예제를 제공합니다. 먼저, 크기를 구하려는 파일을 나타내는 File 객체를 만들어야 합니다. File 객체를 생성하는 방법은 다음과 같습니다: Filef

Jul 24, 2023 pm 07:55 PM

Java의 String.valueOf() 함수를 사용하여 기본 데이터 유형을 문자열로 변환 Java 개발에서 기본 데이터 유형을 문자열로 변환해야 할 때 일반적인 방법은 String 클래스의 valueOf() 함수를 사용하는 것입니다. 이 함수는 기본 데이터 유형의 매개변수를 허용하고 해당 문자열 표현을 반환할 수 있습니다. 이 기사에서는 기본 데이터 유형 변환을 위해 String.valueOf() 함수를 사용하는 방법을 살펴보고 다음과 같은 몇 가지 코드 예제를 제공합니다.

PHP Blob을 파일로 변환하는 방법 PHP Blob을 파일로 변환하는 방법 Mar 16, 2023 am 10:47 AM

PHP Blob을 파일로 변환하는 방법: 1. PHP 샘플 파일을 생성합니다. 2. "function blobToFile(blob) {return new File([blob], 'screenshot.png', { type: 'image/jpeg' })를 통해 } ” 메소드를 사용하여 Blob을 파일로 변환할 수 있습니다.

C 언어의 return 사용법에 대한 자세한 설명 C 언어의 return 사용법에 대한 자세한 설명 Oct 07, 2023 am 10:58 AM

C 언어에서 return의 사용법은 다음과 같습니다. 1. 반환 값 유형이 void인 함수의 경우 return 문을 사용하여 함수 실행을 조기에 종료할 수 있습니다. 2. 반환 값 유형이 void가 아닌 함수의 경우 return 문은 함수 실행을 종료하는 것입니다. 결과는 호출자에게 반환됩니다. 3. 함수 실행을 조기에 종료합니다. 함수 내부에서는 return 문을 사용하여 함수 실행을 조기에 종료할 수 있습니다. 함수가 값을 반환하지 않는 경우.

char 배열을 문자열로 변환하는 방법 char 배열을 문자열로 변환하는 방법 Jun 09, 2023 am 10:04 AM

char 배열을 문자열로 변환하는 방법: 할당을 통해 달성할 수 있습니다. char 배열이 문자열에 직접 값을 할당하고 실행하도록 하려면 {char a[]=" abc d\0efg ";string s=a;} 구문을 사용합니다. 변환을 완료하는 코드입니다.

Java의 File.renameTo() 함수를 사용하여 파일 이름 바꾸기 Java의 File.renameTo() 함수를 사용하여 파일 이름 바꾸기 Jul 25, 2023 pm 03:45 PM

Java의 File.renameTo() 함수를 사용하여 파일 이름을 바꿉니다. Java 프로그래밍에서는 파일 이름을 바꿔야 하는 경우가 많습니다. Java는 파일 작업을 처리하기 위해 File 클래스를 제공하며 renameTo() 함수는 파일 이름을 쉽게 바꿀 수 있습니다. 이 기사에서는 Java의 File.renameTo() 함수를 사용하여 파일 이름을 바꾸는 방법을 소개하고 해당 코드 예제를 제공합니다. File.renameTo() 함수는 File 클래스의 메서드입니다.

기능은 무슨 뜻인가요? 기능은 무슨 뜻인가요? Aug 04, 2023 am 10:33 AM

함수는 특정 기능을 포함하는 재사용 가능한 코드 블록으로, 입력 매개변수를 받아들이고 특정 작업을 수행하며 결과를 반환하는 것이 목적입니다. 코드 재사용성과 유지 관리성을 향상시키는 코드입니다.

See all articles