The most complete collection of commonly used PHP tools
Jul 29, 2016 am 09:11 AM<?php /** * 助手類 * @author www.shouce.ren */ class Helper { /** * 判斷當(dāng)前服務(wù)器系統(tǒng) * @return string */ public static function getOS(){ if(PATH_SEPARATOR == ':'){ return 'Linux'; }else{ return 'Windows'; } } /** * 當(dāng)前微妙數(shù) * @return number */ public static function microtime_float() { list ( $usec, $sec ) = explode ( " ", microtime () ); return (( float ) $usec + ( float ) $sec); } /** * 切割utf-8格式的字符串(一個(gè)漢字或者字符占一個(gè)字節(jié)) * * @author zhao jinhan * @version v1.0.0 * */ public static function truncate_utf8_string($string, $length, $etc = '...') { $result = ''; $string = html_entity_decode ( trim ( strip_tags ( $string ) ), ENT_QUOTES, 'UTF-8' ); $strlen = strlen ( $string ); for($i = 0; (($i < $strlen) && ($length > 0)); $i ++) { if ($number = strpos ( str_pad ( decbin ( ord ( substr ( $string, $i, 1 ) ) ), 8, '0', STR_PAD_LEFT ), '0' )) { if ($length < 1.0) { break; } $result .= substr ( $string, $i, $number ); $length -= 1.0; $i += $number - 1; } else { $result .= substr ( $string, $i, 1 ); $length -= 0.5; } } $result = htmlspecialchars ( $result, ENT_QUOTES, 'UTF-8' ); if ($i < $strlen) { $result .= $etc; } return $result; } /** * 遍歷文件夾 * @param string $dir * @param boolean $all true表示遞歸遍歷 * @return array */ public static function scanfDir($dir='', $all = false, &$ret = array()){ if ( false !== ($handle = opendir ( $dir ))) { while ( false !== ($file = readdir ( $handle )) ) { if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) { $cur_path = $dir . '/' . $file; if (is_dir ( $cur_path )) { $ret['dirs'][] =$cur_path; $all && self::scanfDir( $cur_path, $all, $ret); } else { $ret ['files'] [] = $cur_path; } } } closedir ( $handle ); } return $ret; } /** * 郵件發(fā)送 * @param string $toemail * @param string $subject * @param string $message * @return boolean */ public static function sendMail($toemail = '', $subject = '', $message = '') { $mailer = Yii::createComponent ( 'application.extensions.mailer.EMailer' ); //郵件配置 $mailer->SetLanguage('zh_cn'); $mailer->Host = Yii::app()->params['emailHost']; //<strong>發(fā)送郵件</strong>服務(wù)器 $mailer->Port = Yii::app()->params['emailPort']; //郵件端口 $mailer->Timeout = Yii::app()->params['emailTimeout'];//郵件發(fā)送超時(shí)時(shí)間 $mailer->ContentType = 'text/html';//設(shè)置html格式 $mailer->SMTPAuth = true; $mailer->Username = Yii::app()->params['emailUserName']; $mailer->Password = Yii::app()->params['emailPassword']; $mailer->IsSMTP (); $mailer->From = $mailer->Username; // 發(fā)件人郵箱 $mailer->FromName = Yii::app()->params['emailFormName']; // 發(fā)件人姓名 $mailer->AddReplyTo ( $mailer->Username ); $mailer->CharSet = 'UTF-8'; // 添加郵件日志 $modelMail = new MailLog (); $modelMail->accept = $toemail; $modelMail->subject = $subject; $modelMail->message = $message; $modelMail->send_status = 'waiting'; $modelMail->save (); // <strong>發(fā)送郵件</strong> $mailer->AddAddress ( $toemail ); $mailer->Subject = $subject; $mailer->Body = $message; if ($mailer->Send () === true) { $modelMail->times = $modelMail->times + 1; $modelMail->send_status = 'success'; $modelMail->save (); return true; } else { $error = $mailer->ErrorInfo; $modelMail->times = $modelMail->times + 1; $modelMail->send_status = 'failed'; $modelMail->error = $error; $modelMail->save (); return false; } } /** * 判斷字符串是utf-8 還是<strong>GB2312</strong> * @param unknown $str * @param string $default * @return string */ public static function utf8_<strong>GB2312</strong>($str, $default = '<strong>GB2312</strong>') { $str = preg_replace("/[\x01-\x7F]+/", "", $str); if (empty($str)) return $default; $preg = array( "<strong>GB2312</strong>" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正則判斷是否是<strong>GB2312</strong> "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u", //正則判斷是否是漢字(utf8編碼的條件了),這個(gè)范圍實(shí)際上已經(jīng)包含了繁體中文字了 ); if ($default == '<strong>GB2312</strong>') { $option = 'utf-8'; } else { $option = '<strong>GB2312</strong>'; } if (!preg_match($preg[$default], $str)) { return $option; } $str = @iconv($default, $option, $str); //不能轉(zhuǎn)成 $option, 說明原來的不是 $default if (empty($str)) { return $option; } return $default; } /** * utf-8和<strong>GB2312</strong>自動轉(zhuǎn)化 * @param unknown $string * @param string $outEncoding * @return unknown|string */ public static function safeEncoding($string,$outEncoding = 'UTF-8') { $encoding = "UTF-8"; for($i = 0; $i < strlen ( $string ); $i ++) { if (ord ( $string {$i} ) < 128) continue; if ((ord ( $string {$i} ) & 224) == 224) { // 第一個(gè)字節(jié)判斷通過 $char = $string {++ $i}; if ((ord ( $char ) & 128) == 128) { // 第二個(gè)字節(jié)判斷通過 $char = $string {++ $i}; if ((ord ( $char ) & 128) == 128) { $encoding = "UTF-8"; break; } } } if ((ord ( $string {$i} ) & 192) == 192) { // 第一個(gè)字節(jié)判斷通過 $char = $string {++ $i}; if ((ord ( $char ) & 128) == 128) { // 第二個(gè)字節(jié)判斷通過 $encoding = "<strong>GB2312</strong>"; break; } } } if (strtoupper ( $encoding ) == strtoupper ( $outEncoding )) return $string; else return @iconv ( $encoding, $outEncoding, $string ); } /** * 返回二維數(shù)組中某個(gè)鍵名的所有值 * @param input $array * @param string $key * @return array */ public static function array_key_values($array =array(), $key='') { $ret = array(); foreach((array)$array as $k=>$v){ $ret[$k] = $v[$key]; } return $ret; } /** * 判斷 文件/目錄 是否可寫(取代系統(tǒng)自帶的 is_writeable 函數(shù)) * @param string $file 文件/目錄 * @return boolean */ public static function is_writeable($file) { if (is_dir($file)){ $dir = $file; if ($fp = @fopen("$dir/test.txt", 'w')) { @fclose($fp); @unlink("$dir/test.txt"); $writeable = 1; } else { $writeable = 0; } } else { if ($fp = @fopen($file, 'a+')) { @fclose($fp); $writeable = 1; } else { $writeable = 0; } } return $writeable; } /** * 格式化單位 */ static public function byteFormat( $size, $dec = 2 ) { $a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" ); $pos = 0; while ( $size >= 1024 ) { $size /= 1024; $pos ++; } return round( $size, $dec ) . " " . $a[$pos]; } /** * 下拉框,單選按鈕 自動選擇 * * @param $string 輸入字符 * @param $param 條件 * @param $type 類型 * selected checked * @return string */ static public function selected( $string, $param = 1, $type = 'select' ) { $true = false; if ( is_array( $param ) ) { $true = in_array( $string, $param ); }elseif ( $string == $param ) { $true = true; } $return=''; if ( $true ) $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"'; echo $return; } /** * 下載遠(yuǎn)程圖片 * @param string $url 圖片的絕對url * @param string $filepath 文件的完整路徑(例如/www/images/test) ,此函數(shù)會自動根據(jù)圖片url和http頭信息確定圖片的后綴名 * @param string $filename 要保存的文件名(不含擴(kuò)展名) * @return mixed 下載成功返回一個(gè)描述圖片信息的數(shù)組,下載失敗則返回false */ static public function downloadImage($url, $filepath, $filename) { //服務(wù)器返回的頭信息 $responseHeaders = array(); //原始圖片名 $originalfilename = ''; //圖片的后綴名 $ext = ''; $ch = curl_init($url); //設(shè)置curl_exec返回的值包含Http頭 curl_setopt($ch, CURLOPT_HEADER, 1); //設(shè)置curl_exec返回的值包含Http內(nèi)容 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //設(shè)置抓取跳轉(zhuǎn)(http 301,302)后的頁面 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //設(shè)置最多的HTTP重定向的數(shù)量 curl_setopt($ch, CURLOPT_MAXREDIRS, 3); //服務(wù)器返回的數(shù)據(jù)(包括http頭信息和內(nèi)容) $html = curl_exec($ch); //獲取此次抓取的相關(guān)信息 $httpinfo = curl_getinfo($ch); curl_close($ch); if ($html !== false) { //分離response的header和body,由于服務(wù)器可能使用了302跳轉(zhuǎn),所以此處需要將字符串分離為 2+跳轉(zhuǎn)次數(shù) 個(gè)子串 $httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']); //倒數(shù)第二段是服務(wù)器最后一次response的http頭 $header = $httpArr[count($httpArr) - 2]; //倒數(shù)第一段是服務(wù)器最后一次response的內(nèi)容 $body = $httpArr[count($httpArr) - 1]; $header.="\r\n"; //獲取最后一次response的header信息 preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches); if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) { for ($i = 0; $i < count($matches[1]); $i++) { if (array_key_exists($i, $matches[2])) { $responseHeaders[$matches[1][$i]] = $matches[2][$i]; } } } //獲取圖片后綴名 if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) { $originalfilename = $matches[0]; $ext = $matches[1]; } else { if (array_key_exists('Content-Type', $responseHeaders)) { if (0 < preg_match('{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) { $ext = $extmatches[1]; } } } //保存文件 if (!empty($ext)) { //如果目錄不存在,則先要創(chuàng)建目錄 if(!is_dir($filepath)){ mkdir($filepath, 0777, true); } $filepath .= '/'.$filename.".$ext"; $local_file = fopen($filepath, 'w'); if (false !== $local_file) { if (false !== fwrite($local_file, $body)) { fclose($local_file); $sizeinfo = getimagesize($filepath); return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME)); } } } } return false; } /** * 查找ip是否在某個(gè)段位里面 * @param string $ip 要查詢的ip * @param $arrIP 禁止的ip * @return boolean */ public static function ipAccess($ip='0.0.0.0', $arrIP = array()){ $access = true; $ip && $arr_cur_ip = explode('.', $ip); foreach((array)$arrIP as $key=> $value){ if($value == '*.*.*.*'){ $access = false; //禁止所有 break; } $tmp_arr = explode('.', $value); if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) { //前兩段相同 if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){ //第三段為* 或者相同 if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){ //第四段為* 或者相同 $access = false; //在禁止ip列,則禁止訪問 break; } } } } return $access; } /** * @param string $string 原文或者密文 * @param string $operation 操作(ENCODE | DECODE), 默認(rèn)為 DECODE * @param string $key 密鑰 * @param int $expiry 密文有效期, 加密時(shí)候有效, 單位 秒,0 為永久有效 * @return string 處理后的 原文或者 經(jīng)過 base64_encode 處理后的密文 * * @example * * $a = authcode('abc', 'ENCODE', 'key'); * $b = authcode($a, 'DECODE', 'key'); // $b(abc) * * $a = authcode('abc', 'ENCODE', 'key', 3600); * $b = authcode('abc', 'DECODE', 'key'); // 在一個(gè)小時(shí)內(nèi),$b(abc),否則 $b 為空 */ public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) { $ckey_length = 4; // 隨機(jī)密鑰長度 取值 0-32; // 加入隨機(jī)密鑰,可以令密文無任何規(guī)律,即便是原文和密鑰完全相同,加密結(jié)果也會每次不同,增大破解難度。 // 取值越大,密文變動規(guī)律越大,密文變化 = 16 的 $ckey_length 次方 // 當(dāng)此值為 0 時(shí),則不產(chǎn)生隨機(jī)密鑰 $key = md5 ( $key ? $key : 'key' ); //這里可以填寫默認(rèn)key值 $keya = md5 ( substr ( $key, 0, 16 ) ); $keyb = md5 ( substr ( $key, 16, 16 ) ); $keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : ''; $cryptkey = $keya . md5 ( $keya . $keyc ); $key_length = strlen ( $cryptkey ); $string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string; $string_length = strlen ( $string ); $result = ''; $box = range ( 0, 255 ); $rndkey = array (); for($i = 0; $i <= 255; $i ++) { $rndkey [$i] = ord ( $cryptkey [$i % $key_length] ); } for($j = $i = 0; $i < 256; $i ++) { $j = ($j + $box [$i] + $rndkey [$i]) % 256; $tmp = $box [$i]; $box [$i] = $box [$j]; $box [$j] = $tmp; } for($a = $j = $i = 0; $i < $string_length; $i ++) { $a = ($a + 1) % 256; $j = ($j + $box [$a]) % 256; $tmp = $box [$a]; $box [$a] = $box [$j]; $box [$j] = $tmp; $result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) ); } if ($operation == 'DECODE') { if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) { return substr ( $result, 26 ); } else { return ''; } } else { return $keyc . str_replace ( '=', '', base64_encode ( $result ) ); } } public static function gbkToUtf8($str){ return iconv("GBK", "UTF-8", $str); } /** * 取得輸入目錄所包含的所有目錄和文件 * 以關(guān)聯(lián)數(shù)組形式返回 * author: flynetcn */ static public function deepScanDir($dir) { $fileArr = array(); $dirArr = array(); $dir = rtrim($dir, '//'); if(is_dir($dir)){ $dirHandle = opendir($dir); while(false !== ($fileName = readdir($dirHandle))){ $subFile = $dir . DIRECTORY_SEPARATOR . $fileName; if(is_file($subFile)){ $fileArr[] = $subFile; } elseif (is_dir($subFile) && str_replace('.', '', $fileName)!=''){ $dirArr[] = $subFile; $arr = self::deepScanDir($subFile); $dirArr = array_merge($dirArr, $arr['dir']); $fileArr = array_merge($fileArr, $arr['file']); } } closedir($dirHandle); } return array('dir'=>$dirArr, 'file'=>$fileArr); } /** * 取得輸入目錄所包含的所有文件 * 以數(shù)組形式返回 * author: flynetcn */ static public function get_dir_files($dir) { if (is_file($dir)) { return array($dir); } $files = array(); if (is_dir($dir) && ($dir_p = opendir($dir))) { $ds = DIRECTORY_SEPARATOR; while (($filename = readdir($dir_p)) !== false) { if ($filename=='.' || $filename=='..') { continue; } $filetype = filetype($dir.$ds.$filename); if ($filetype == 'dir') { $files = array_merge($files, self::get_dir_files($dir.$ds.$filename)); } elseif ($filetype == 'file') { $files[] = $dir.$ds.$filename; } } closedir($dir_p); } return $files; } /** * 刪除文件夾及其文件夾下所有文件 */ public static function deldir($dir) { //先刪除目錄下的文件: $dh=opendir($dir); while ($file=readdir($dh)) { if($file!="." && $file!="..") { $fullpath=$dir."/".$file; if(!is_dir($fullpath)) { unlink($fullpath); } else { self::deldir($fullpath); } } } closedir($dh); //刪除當(dāng)前文件夾: if(rmdir($dir)) { return true; } else { return false; } } /** * js 彈窗并且跳轉(zhuǎn) * @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(); } /** * 頁面跳轉(zhuǎn) * @param string $url * @return js */ static public function headerUrl($url) { echo "<script type='text/javascript'>location.href='{$url}';</script>"; exit(); } /** * 彈窗關(guān)閉 * @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(); } /** * 系統(tǒng)基本參數(shù)上傳圖片專用 * @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] = self::htmlString($_value); //遞歸 } } elseif (is_object($_date)) { foreach ($_date as $_key=>$_value) { $_string->$_key = self::htmlString($_value); //遞歸 } } else { $_string = htmlspecialchars($_date); } return $_string; } /** * 數(shù)據(jù)庫輸入過濾 * @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(); } } /** * 驗(yàn)證是否為空 * @param string $str * @param string $name * @return bool (true or false) */ static function validateEmpty($str, $name) { if (empty($str)) { self::alertBack('警告:' .$name . '不能為空!'); } } /** * 驗(yàn)證是否相同 * @param string $str1 * @param string $str2 * @param string $alert * @return JS */ static function validateAll($str1, $str2, $alert) { if ($str1 != $str2) self::alertBack('警告:' .$alert); } /** * 驗(yàn)證ID * @param Number $id * @return JS */ static function validateId($id) { if (empty($id) || !is_numeric($id)) self::alertBack('警告:參數(shù)錯(cuò)誤!'); } /** * 格式化字符串 * @param string $str * @return string */ static public function formatStr($str) { $arr = array(' ', ' ', '&', '@', '#', '%', '\'', '"', '\\', '/', '.', ',', '$', '^', '*', '(', ')', '[', ']', '{', '}', '|', '~', '`', '?', '!', ';', ':', '-', '_', '+', '='); foreach ($arr as $v) { $str = str_replace($v, '', $str); } return $str; } /** * 格式化時(shí)間 * @param int $time 時(shí)間戳 * @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; } /** * 獲得真實(shí)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); } /** * 創(chuàng)建目錄 * @param string $dir */ static public function createDir($dir) { if (!is_dir($dir)) { mkdir($dir, 0777); } } /** * 創(chuàng)建文件(默認(rèn)為空) * @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 self::mysqlString(trim($_POST[$param])); } elseif ($type=='get') { return self::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); //刪除當(dāng)前文件夾: if(rmdir($dir)) { return true; } else { return false; } } } /** * 驗(yàn)證登陸 */ static public function validateLogin() { if (empty($_SESSION['admin']['user'])) header('Location:/admin/'); } /** * 給已經(jīng)存在的圖片添加水印 * @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); //求<strong>水印圖片</strong>高寬 $src_imginfo = getimagesize(MARK); $src_width = $src_imginfo[0]; $src_height = $src_imginfo[1]; //求出<strong>水印圖片</strong>的實(shí)際生成位置 $src_x = $width - $src_width - 10; $src_y = $height - $src_height - 10; //新建一個(gè)真彩色圖像 $nimage = imagecreatetruecolor($width, $height); //拷貝上傳圖片到真彩圖像 imagecopy($nimage, $dst_im, 0, 0, 0, 0, $width, $height); //按坐標(biāo)位置拷貝<strong>水印圖片</strong>到真彩圖像上 imagecopy($nimage, $src_im, $src_x, $src_y, 0, 0, $src_width, $src_height); //分情況輸出生成后的<strong>水印圖片</strong> 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,單字節(jié)截取模式 * @access public * @param string $str 需要截取的字符串 * @param int $slen 截取的長度 * @param int $startdd 開始標(biāo)記處 * @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中文截取,單字節(jié)截取模式 * * @access public * @param string $str 需要截取的字符串 * @param int $slen 截取的長度 * @param int $startdd 開始標(biāo)記處 * @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以下版本,與數(shù)據(jù)庫varchar一致,這里使用按字節(jié)截取 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; } /** * 刪除圖片,根據(jù)圖片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', '<strong>GB2312</strong>', $file_path); //對可能出現(xiàn)的中文名稱進(jìn)行轉(zhuǎn)碼 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; //判斷文件是否結(jié)束 while (!feof($fp) && ($file_size-$file_count>0)) { $file_data = fread($fp, $buffer); $file_count += $buffer; echo $file_data; } fclose($fp); //關(guān)閉文件 } }
下載地址 http://www.shouce.ren/post/view/id/1700
以上就介紹了最完整PHP常用工具類大全,包括了水印圖片,發(fā)送郵件,GB2312方面的內(nèi)容,希望對PHP教程有興趣的朋友有所幫助。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Use Java's File.length() function to get the size of a file. File size is a very common requirement when dealing with file operations. Java provides a very convenient way to get the size of a file, that is, using the length() method of the File class. . This article will introduce how to use this method to get the size of a file and give corresponding code examples. First, we need to create a File object to represent the file we want to get the size of. Here is how to create a File object: Filef

To learn more about open source, please visit: 51CTO Hongmeng Developer Community https://ost.51cto.com Running environment DAYU200:4.0.10.16SDK: 4.0.10.15IDE: 4.0.600 1. To create an application, click File- >newFile->CreateProgect. Select template: [OpenHarmony] EmptyAbility: Fill in the project name, shici, application package name com.nut.shici, and application storage location XXX (no Chinese, special characters, or spaces). CompileSDK10, Model: Stage. Device

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

Convert basic data types to strings using Java's String.valueOf() function In Java development, when we need to convert basic data types to strings, a common method is to use the valueOf() function of the String class. This function can accept parameters of basic data types and return the corresponding string representation. In this article, we will explore how to use the String.valueOf() function for basic data type conversions and provide some code examples to

Use Java's File.renameTo() function to rename files. In Java programming, we often need to rename files. Java provides the File class to handle file operations, and its renameTo() function can easily rename files. This article will introduce how to use Java's File.renameTo() function to rename files and provide corresponding code examples. The File.renameTo() function is a method of the File class.

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Method of converting char array to string: It can be achieved by assignment. Use {char a[]=" abc d\0efg ";string s=a;} syntax to let the char array directly assign a value to string, and execute the code to complete the conversion.

Use java's File.getParent() function to get the parent path of a file. In Java programming, we often need to operate files and folders. Sometimes, we need to get the parent path of a file, which is the path of the folder where the file is located. Java's File class provides the getParent() method to obtain the parent path of a file or folder. The File class is Java's abstract representation of files and folders. It provides a series of methods for operating files and folders. Among them, get
