PHP常用工具方法集...

PHP常用工具方法集,更新時間? 2018-7-14

<?php
/*** 常用工具方法集* Author: zj*//**
工具總述
1.加密解密
2.生成隨機字符串
3.獲取文件擴展名(后綴)
4.文件大小格式化
5.替換標簽字符
6.列出目錄下的文件名
7.獲取當前頁面URL
8.讓瀏覽器強制下載文件
9.字符串顯示長度,超出使用...顯示
10.獲取客戶端真實IP
11.防止SQL注入,判斷是否有非法字符
12.頁面提示與跳轉
13.計算時長
14.寫入日志文件
16.過濾特殊字符的函數  utf-8可用
17.統計文章字數和圖片數
18.封裝頁面跳轉函數
19.獲取當前文件路徑
20.獲取當前文件目錄
21.獲取當前時間字符串
22.獲取時間戳格式化時間字符串*///1.加密解密,$decrypt:0->加密,1->解密
function encryptDecrypt($key, $string, $decrypt){if($decrypt){$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");return $decrypted;}else{$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));return $encrypted;}
}//2.生成隨機字符串
function generateRandomString($length = 10) {$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';$randomString = '';for ($i = 0; $i < $length; $i++) {$randomString .= $characters[rand(0, strlen($characters) - 1)];}return $randomString;
}//3.獲取文件擴展名(后綴)
function getExtension($filename){$myext = substr($filename, strrpos($filename, '.')); //strrpos:最后位置return str_replace('.','',$myext);
}//4.文件大小格式化
function formatSize($size) {$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");if ($size == 0) {return('n/a');} else {//log(x,base):指定了可選的參數 base,log() 返回 logbasex ,否則 log() 返回參數 x 的自然對數;//pow(x,y):返回 x 的 y 次方的冪,如x=4,y=2,結果為16//重點獲取$i:1024*1024*1024...級別對數return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);}
}//5.替換標簽字符
/* 使用方法
$string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself';
$replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '<br />');
echo stringParser($string,$replace_array);*/
function stringParser($string, $replacer){//str_replace對應替換多個字符$result = str_replace(array_keys($replacer), array_values($replacer), $string);return $result;
}//6.列出目錄下的文件名,不列出文件夾名
function listDirFiles($DirPath){if($dir = opendir($DirPath)){while(($file = readdir($dir)) !== false){if(!is_dir($DirPath.$file)){echo "filename: $file<br />";}}}
}//7.獲取當前頁面URL
function curPageURLhost() {$pageURL = 'http';if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";}$pageURL .= "://"; //拼接if ($_SERVER["SERVER_PORT"] != "80") {$pageURL .= $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];} else {$pageURL .= $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];}return $pageURL;
}//7-2.獲取當前頁面URL目錄
function curPageURLaddrCatalog() {$pageURL = curPageURLhost();return $pageURL=substr($pageURL,0, strrpos($pageURL, '/')+1);
}//8.讓瀏覽器強制下載文件-原文件名
function download($filepath){if ((isset($filepath))&&(file_exists($filepath))){header("Content-length: ".filesize($filepath));header('Content-Type: application/octet-stream');header('Content-Disposition: attachment; filename="' . substr($filepath,strrpos($filepath, '/')+1, strlen($filepath)) . '"');readfile("$filepath");} else {echo "文件不存在!";}
}//8.讓瀏覽器強制下載文件-文件重命名
function downloadScel($filepath, $filename){if ((isset($filepath))&&(file_exists($filepath))){header("Content-length: ".filesize($filepath));header('Content-Type: application/octet-stream');header('Content-Disposition: attachment; filename="' . $filename.'.'.getExtension($filepath) . '"');readfile("$filepath");} else {echo "文件不存在!";}
}//9.字符串顯示長度,超出使用...顯示
/*Utf-8、gb2312都支持的漢字截取函數cut_str(字符串, 截取長度, 開始長度, 編碼);編碼默認為 utf-8開始長度默認為 0顯示不能超過多少字符,超出的長度用…表示
*/
function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){if($code == 'UTF-8'){$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";preg_match_all($pa, $string, $t_string);if(count($t_string[0]) - $start > $sublen){return join('', array_slice($t_string[0], $start, $sublen))."...";}return join('', array_slice($t_string[0], $start, $sublen));}else{$start = $start*2;$sublen = $sublen*2;$strlen = strlen($string);$tmpstr = '';for($i=0; $i<$strlen; $i++){if($i>=$start && $i<($start+$sublen)){if(ord(substr($string, $i, 1))>129){$tmpstr.= substr($string, $i, 2);}else{$tmpstr.= substr($string, $i, 1);}}if(ord(substr($string, $i, 1))>129){$i++;}}if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";return $tmpstr;}
}//10.獲取客戶端真實IP
function getIp() {if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))$ip = getenv("HTTP_CLIENT_IP");elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))$ip = getenv("HTTP_X_FORWARDED_FOR");elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))$ip = getenv("REMOTE_ADDR");elseif (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))$ip = $_SERVER['REMOTE_ADDR'];else$ip = "unknown";return ($ip);
}//11.防止SQL注入,判斷是否有非法字符
function injCheck($sql_str) {$check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);if ($check) {echo '非法字符!!';exit;} else {return $sql_str;}
}//12.頁面提示與跳轉
function message($msgTitle,$message,$jumpUrl){$str = '<!DOCTYPE HTML>';$str .= '<html>';$str .= '<head>';$str .= '<meta charset="utf-8">';$str .= '<title>頁面提示</title>';$str .= '<style type="text/css">';$str .= '*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:14px/18px Tahoma, Arial,  sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}';$str .= '</style>';$str .= '</head>';$str .= '<body>';$str .= '<div>';$str .= '<h3>'.$msgTitle.'</h3>';$str .= '<div>';$str .= '<h4>'.$message.'</h4>';$str .= '<p>系統將在 <span style="color:blue;font-weight:bold">3</span> 秒后自動跳轉,如果不想等待,直接點擊 <a href="'.$jumpUrl.'">這里</a> 跳轉</p>';$str .= "<script>setTimeout('location.replace(\'".$jumpUrl."\')',2000)</script>";$str .= '</div>';$str .= '</div>';$str .= '</body>';$str .= '</html>';echo $str;
}//13.計算時長
function changeTimeType($seconds) {if ($seconds > 3600) {$hours = intval($seconds / 3600);$minutes = $seconds % 3600;$time = $hours . ":" . gmstrftime('%M:%S', $minutes);} else {$time = gmstrftime('%H:%M:%S', $seconds);}return $time;
}/*** 14.寫入日志文件* @parm1	: 日志文件名稱* @parm2	: 記錄的信息*/
function logFile($filename, $msg){$str = "[".date("Y-m-d H:i:s",time())."] ".$msg . PHP_EOL;file_put_contents($filename, $str,FILE_APPEND);
}//16.過濾特殊字符的函數  utf-8可用,過濾例如'&'中的'amp;'
function filterSpechars ($string){return preg_replace('/[\x00-\x1F\x7F-\x9F]/u', '', $string);
}/*** 17.統計文章字數和圖片數* 參數:文章內容字符串* 返回:array*/
function countWords($str){$str = trim($str);$pattern = "/\[#img_[0-9]+_[a-z]*_[0-9]+_[a-zA-Z]*/i";#統計圖片數preg_match_all($pattern, $str, $match_arrs);$picCount = count($match_arrs[0]);##增加新的圖片記數方式preg_match_all('/<img /i',$str,$match_arrs);$picCount = $picCount + count($match_arrs[0]);#統計字數$str = preg_replace($pattern, "", $str);$str = preg_replace("/<img([^>].+)>/iU","", $str);    ##去掉圖片標簽$str = str_replace(' ','', $str);               ##去掉空格$wordCount = mb_strwidth(trim(strip_tags($str)));return array('wordCount'=>$wordCount,'picCount'=>$picCount,);
}/** 18.封裝頁面跳轉函數* @param $url 目標地址* @param $info 提示信息* @param $sec 等待時間* return void
*/
function jump($url,$info=null,$sec=3)
{if(is_null($info)){header("Location:$url");}else{// header("Refersh:$sec;URL=$url");echo"<meta http-equiv=\"refresh\" content=".$sec.";URL=".$url.">";echo $info;}die(); //結束當前腳本運行
}/** 19.獲取當前文件路徑* return path
*/
function getThisPath()
{return __FILE__;
}/** 20.獲取當前文件目錄* 等價方法:getcwd();* return path
*/
function getThisCatalog()
{return __DIR__.'\\';
}/** 21.獲取當前時間字符串* @param 可選參數,格式化* return date
*/
function getNowDateTime($format='Y-m-d H:i:s')
{return date($format);
}/** 22.獲取時間戳格式化時間字符串* @param 時間戳* @param 可選參數,格式化* return date
*/
function getFormatDateTime($timestamp, $format='Y-m-d H:i:s')
{return date($format, $timestamp);
}

?

?

?

持續更新中...

?

?

?

?

?

轉載于:https://www.cnblogs.com/qq1995/p/10359009.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279873.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279873.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279873.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

一題多解 面試題

最近在其他論壇上看到幾個網友的面試題&#xff0c;這些天&#xff0c;QQ群內的人都在討論怎么解答才最簡單&#xff0c;下面列出題目&#xff1a; 文件a&#xff1a; 文件b: a b c a b c b c a b c a c b a …

什么是Google On.Here,以及如何設置?

Google Wi-Fi is similar to other mesh Wi-Fi systems, but one big feature separates it from the pack: Google On.Here. Google Wi-Fi與其他網狀Wi-Fi系統相似&#xff0c;但其中一個重要功能將其與眾不同&#xff1a;Google On.Here。 發生什么了&#xff1f; (What Is O…

一張圖看懂 SQL 的各種 join 用法

原文鏈接https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins 轉載于:https://www.cnblogs.com/xuchao0506/p/10559951.html

1Python全棧之路系列Web框架介紹

Python全棧之路系列之Web框架介紹 所有的語言Web框架本質其實就是起一個socket服務端,監聽一個端口,然后運行起來 Web框架包含兩部分,一部分是socket,另外一部分是業務的邏輯處理,根據請求的不同做不同的處理 Python的Web框架分成了兩類, 即包含socket也包含業務邏輯處理的(tor…

『 再看.NET7』數值類型

在C#中&#xff0c;有int16&#xff0c;用short來定義&#xff1b;有int32&#xff0c;用int定義&#xff1b;用int64&#xff0c;用long來定義。在.NET7中&#xff0c;添加了int128&#xff0c;和unint128&#xff0c;位數更大的整型。var i16 short.MaxValue; Console.Write…

獲取幫助命令

whatis 基于數據庫的查找,查找內容比較慢 優點&#xff1a;查找速度快 缺點&#xff1a;沒有實時性 [rootlocalhost ~]# whatis ls ls (1) - list directory contents ls (1p) - list directory contents 數據庫文件 Centos6:/…

筆記本電腦升級固態硬盤好嗎_如何升級筆記本電腦硬盤

筆記本電腦升級固態硬盤好嗎Upgrading your laptop’s hard drive is a great way to get some extra life out of an old machine (or resurrect a dead one). Read on as we walk you through the prep work, the installation, and the followup. 升級筆記本電腦的硬盤驅動器…

購物單

小明剛剛找到工作&#xff0c;老板人很好&#xff0c;只是老板夫人很愛購物。老板忙的時候經常讓小明幫忙到商場代為購物。小明很厭煩&#xff0c;但又不好推辭。 這不&#xff0c;XX大促銷又來了&#xff01;老板夫人開出了長長的購物單&#xff0c;都是有打折優惠的。 …

Seay源代碼審計系統

這是一款基于C#語言開發的一款針對PHP代碼安全性審計的系統&#xff0c;主要運行于Windows系統上。這款軟件能夠發現SQL注入、代碼執行、命令執行、文件包含、文件上傳、繞過轉義防護、拒絕服務、XSS跨站、信息泄露、任意URL跳轉等漏洞。 下載鏈接 https://pan.baidu.com/s/1V…

dotnet 世界猜測 隨機數的小測試

這是一個半技術向的博客&#xff0c;主題來源于我讀過的某本書的片段&#xff0c;這是一個稍稍有些前置知識的故事&#xff0c;主題的大概內容就是假定世界存在某個規則序列&#xff0c;通過一代代的探索&#xff0c;可以獲取到此序列的內容。本文將模擬此情形&#xff0c;寫一…

python 批量修改密碼

下午閑來無事&#xff0c;就搞個批量密碼修改工具玩玩... #!/usr/bin/env python import paramiko import time ip_list(ip1,ip2) log_fileopen(mpwdok.log,w) log_file1open(mpwderr.log,w) for ip in ip_list: try: s paramiko.Transport((ip, 22)) s.c…

如何在Android Wear上節省電池壽命

If you’re rocking Android on your wrist, there’s a chance you’ve learned to rely on its convenience pretty heavily. And if you’re in that position, then you probably also know how annoying it can be if your watch runs out of juice in the middle of the …

css3 偽類選擇器

1.target&#xff1a;表示當前的url片段的元素類型&#xff0c;這個元素必須是E &#xff08;作用類似于選項卡&#xff09; 2.&#xff1a;&#xff1a;before{content&#xff1a;“要添加的內容”} 添加到......之前 3.rgb&#xff08;&#xff09; 顏色 4.rgba&#xf…

城市統計【BFS】

題目大意&#xff1a; 中山市的地圖是一個n*n的矩陣&#xff0c;其中標號為1的表示商業區&#xff0c;標號為0的表示居民區。為了考察市內居民區與商業區的距離&#xff0c;并對此作出評估&#xff0c;市長希望你能夠編寫一個程序完成這一任務。  居民區i到商業區的距離指的是…

使用 DataAnnotations(數據注解)實現通用模型數據校驗

.net 跨平臺參數校驗的意義在實際項目開發中&#xff0c;無論任何方式、任何規模的開發模式&#xff0c;項目中都離不開對接入數據模型參數的合法性校驗&#xff0c;目前普片的開發模式基本是前后端分離&#xff0c;當用戶在前端頁面中輸入一些表單數據時&#xff0c;點擊提交按…

網線的做法 及 POE的介紹

網線的做法 以太網線采用差分方式傳輸。所謂差分方式傳輸&#xff0c;就是發送端在兩條信號線上傳輸幅值相等相位相反的電信號&#xff0c;接收端對接受的兩條線信號作減法運算&#xff0c;這樣獲得幅值翻倍的信號。其抗干擾的原理是&#xff1a;假如兩條信號線都受到了同樣&am…

unity 使用tile_如何使用Tile從網上查找電話

unity 使用tileTile is a fantastic little gadget that can help you find your lost keys or wallet. However, it can also locate and ring your phone, even if you never buy a single physical Tile. Here’s how to find your lost phone using the Tile app on the we…

你與一份好簡歷之間的距離

閱讀本文大概需要 2.7 分鐘。每年年初都是企業的招聘旺季&#xff0c;對應的三四月份絕對跳槽、找工作的好時機&#xff0c;業內經常稱呼這兩個月為金三銀四。實力雄厚的人&#xff0c;那個月找工作問題都不大&#xff0c;但是也會盡量挑選個好時機&#xff0c;能有更多的選擇。…

Python 循環刪除指定文件夾下所有的.longtian類型文件

# -*- coding: utf-8 -*-import os#遍歷文件夾刪除文件 def traversing_dir(rootDir):#遍歷根目錄for root,dirs,files in os.walk(rootDir):for file in files:#文件后綴名extFileos.path.splitext(file)[1]if extFile".longtian":os.remove(os.path.join(root,file…

《ASP.NET Core 6框架揭秘實例》演示[35]:利用Session保留語境

客戶端和服務器基于HTTP的消息交換就好比兩個完全沒有記憶能力的人在交流&#xff0c;每次單一的HTTP事務體現為一次“一問一答”的對話。單一的對話毫無意義&#xff0c;在在同一語境下針對某個主題進行的多次對話才會有結果。會話的目的就是在同一個客戶端和服務器之間建立兩…