# 我覺得有點用的公共函數(I think it's a little bit useful)
---
## 格式化文件大小
```
/**
* [format_size 格式化文件大小]
* @param [int] $size [文件大小]
* @return [float/double] [格式化后的文件大小]
*/
function format_size($size) {
$arr = ['B', 'KB', 'M', 'G', 'T', 'P'];
$i = 0;
while ($size >= 1024) {
$size = $size / 1024;
$i++;
}
// 四舍五入進行返回
return round($size, 4).$arr[$i];
}
```
## 可逆加密算法 encrypt
```
/**
* [encrypt 可逆加密算法]
* @param [type] $data [description]
* @param [type] $key [description]
* @return [type] [description]
*/
function encrypt($data, $key) {
$key = md5($key);
$x = 0;
$len = strlen($data);
$l = strlen($data);
$char = '';
$str = '';
for ($i=0; $i < $len; $i++) {
if ($x == $l) {
$x = 0;
}
$char .= $key{$x};
$x++;
}
for ($i = 0; $i < $len; $i++) {
$str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
}
return base64_encode($str);
}
```
## 解密算法 decrypt
```
/**
* [decrypt 解密算法]
* @param [type] $data [description]
* @param [type] $key [description]
* @return [type] [description]
*/
function decrypt($data, $key) {
$key = md5($key);
$x = 0;
$data = base64_decode($data);
$len = strlen($data);
$l = strlen($key);
$char = "";
$str = "";
for ($i = 0; $i < $len; $i++)
{
if ($x == $l)
{
$x = 0;
}
$char .= substr($key, $x, 1);
$x++;
}
for ($i = 0; $i < $len; $i++)
{
if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
{
$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
}
else
{
$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
}
}
return $str;
}
```
## 導出Excel
```
// 導出excle
function export_to($data,$name=false,$type = 0){
if(!$name){$name=date("Y-m-d-H-i-s",time());}
$PHPExcel = new PHPExcel(); //實例化PHPExcel類,類似于在桌面上新建一個Excel表格
$PHPExcel->getActiveSheet()->fromArray($data);
$PHPExcel->getActiveSheet()->setTitle('Sheet1'); //給當前活動sheet設置名稱
$PHPExcel->setActiveSheetIndex(0);
$fileName = './public/'.date('Y-m-d_', time()).time().'.xlsx';
$saveName = $name.date('Y-m-d', time()).'.xlsx';
$PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel5');//按照指定格式生成Excel文件,‘Excel2007’表示生成2007版本的xlsx,‘Excel5’表示生成2003版本Excel文件
if ($type == 0) {
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告訴瀏覽器輸出07Excel文件
header('Content-Type:application/vnd.ms-excel');//告訴瀏覽器將要輸出Excel03版本文件
header('Content-Disposition: attachment;filename="'.$saveName.'"');//告訴瀏覽器輸出瀏覽器名稱
// header('Content-Disposition: attachment;filename="01simple.xlsx"');//告訴瀏覽器輸出瀏覽器名稱
header('Cache-Control: max-age=0');//禁止緩存
$PHPWriter->save("php://output");
}else{
$PHPWriter->save($fileName); //表示在$path路徑下面生成demo.xlsx文件
}
}
```
## 無限極分類樹
```
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $keys = 'id', $sort = 'asc', $root = 0)
{
// 創建Tree
$tree = array();
if (is_array($list)) {
// 創建基于主鍵的數組引用
$refer = array();
foreach ($list as $key => $data) {
$list[$key][$child] = [];
$refer [$data[$pk]] = &$list[$key];
}
foreach ($list as $key => $data) {
// 判斷是否存在parent
$parentId = $data[$pid];
if ($root == $parentId) {
$tree [] = &$list[$key];
$tree = my_sort($tree,$keys,$sort,SORT_NUMERIC);
} else {
if (isset ($refer [$parentId])) {
$parent = &$refer[$parentId];
$parent[$child] [] = &$list[$key];
$parent[$child] = my_sort($parent[$child],$keys,$sort,SORT_NUMERIC);
}
}
}
}
return $tree;
}
```
## 系統郵件發送函數
```
/**
* 系統郵件發送函數
* @param string $tomail 接收郵件者郵箱
* @param string $name 接收郵件者名稱
* @param string $subject 郵件主題
* @param string $body 郵件內容
* @param string $attachment 附件列表
* @return boolean
* @author static7 <static7@qq.com>
使用方法:
$toemail='111111@qq.com';
$name = 'dqwdqqwdq';//收件人昵稱
$subject='注冊驗證碼';
$mail_tpl = model('MailTpl')->where('type', 'register')->find()->toArray();
$content = str_replace("\$code","123456",$mail_tpl['content']);
$result = send_mail($toemail,$name,$subject,$content);
dump($result);
*/
function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) {
$config_mail = model('Mail')->find()->toArray();
$shop = model('Config')->find();
$mail = new \PHPMailer(); //實例化PHPMailer對象
$mail->CharSet = 'UTF-8'; //設定郵件編碼,默認ISO-8859-1,如果發中文此項必須設置,否則亂碼
$mail->IsSMTP(); // 設定使用SMTP服務
$mail->SMTPDebug = 0; // SMTP調試功能 0=關閉 1 = 錯誤和消息 2 = 消息
$mail->SMTPAuth = true; // 啟用 SMTP 驗證功能
if($config_mail['secure']){
$mail->SMTPSecure = 'ssl'; // 使用安全協議Enable TLS encryption, `ssl` also accepted
}else{
$mail->SMTPSecure = 'tls'; // 使用安全協議Enable TLS encryption, `ssl` also accepted
}
$mail->Host = $config_mail['host']; // SMTP 服務器
$mail->Port = $config_mail['port']; // SMTP服務器的端口號
$mail->Username = $config_mail['user']; // SMTP服務器用戶名
$mail->Password = $config_mail['pass']; // SMTP服務器密碼
$mail->SetFrom($config_mail['user'], $shop['title']);
$replyEmail = $config_mail['replyTo']; //留空則為發件人EMAIL
$replyName = '發送回復'; //回復名稱(留空則為發件人名稱)
$mail->AddReplyTo($replyEmail, $replyName);
$mail->Subject = $subject;
$mail->MsgHTML($body);
$mail->AddAddress($tomail, $name);
if (is_array($attachment)) { // 添加附件
foreach ($attachment as $file) {
is_file($file) && $mail->AddAttachment($file);
}
}
return $mail->Send() ? true : $mail->ErrorInfo;
}
```
## 獲取當前url地址
```
/**
* [getActionUrl description]獲取當前url
* @return [type] [description]
*/
function getActionUrl(){
$module = strtolower(request()->module());
$controller = strtolower(request()->controller());
$action = strtolower(request()->action());
return $module.'/'.$controller.'/'.$action;
}
```
## 截取多少長度的字符串并以省略號代替超過的部分
```php
if (!function_exists('strCut')) {
function strCut($str, $length)//$str為要進行截取bai的字符串,$length為截取長度(du漢字算一個字,字母算半個字)zhi
{
$str = trim($str);
$string = "";
if (strlen($str) > $length) {
for ($i = 0; $i < $length; $i++) {
if (ord($str) > 127) {
$string .= $str[$i] . $str[$i + 1] . $str[$i + 2];
$i = $i + 2;
} else {
$string .= $str[$i];
}
}
$string .= "...";
return $string;
}
return $str;
}
}
```
## Api請求curl方式
```php
if (!function_exists('api')) {
/**
* @param string $url
* @param string $params
* @param string $method
* @param array $header
* @throws \Exception
* @return
*/
function api(string $url, string $params = '', string $method = 'GET', array $header = array())
{
$opts = array(
CURLOPT_TIMEOUT => 30,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYHOST => FALSE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => FALSE
);
switch(strtoupper($method)){
case 'GET':
$opts[CURLOPT_URL] = $url.'?';
if (!empty($params)) {
$opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
}
break;
case 'POST':
$opts[CURLOPT_URL] = $url;
$opts[CURLOPT_POST] = TRUE;
$opts[CURLOPT_POSTFIELDS] = $params;
break;
}
$ch = curl_init();
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if($error){
throw new Exception('curl執行出錯');
}
return $result;
}
}
```
## HTTP curl請求API方法
```php
if (!function_exists('httpRequest')) {
function httpRequest($url, $method, $postfields = null, $headers = [], $debug = false)
{
$method = strtoupper($method);
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在發起連接前等待的時間,如果設置為0,則無限等待 */
curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 設置cURL允許執行的最長秒數 */
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "POST":
curl_setopt($ci, CURLOPT_POST, true);
if (!empty($postfields)) {
$tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
}
break;
default:
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //設置請求方式 */
break;
}
$ssl = preg_match('/^https:\/\//i', $url) ? true : false;
curl_setopt($ci, CURLOPT_URL, $url);
if ($ssl) {
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); // https請求 不驗證證書和hosts
curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false); // 不從證書中檢查SSL加密算法是否存在
}
//curl_setopt($ci, CURLOPT_HEADER, true); /*啟用時會將頭文件的信息作為數據流輸出*/
curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的數量,這個選項是和CURLOPT_FOLLOWLOCATION一起使用的*/
curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ci, CURLINFO_HEADER_OUT, true);
/*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE帶過去** */
$response = curl_exec($ci);
$requestinfo = curl_getinfo($ci);
$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
if ($debug) {
echo "=====post data======\r\n";
var_dump($postfields);
echo "=====info===== \r\n";
print_r($requestinfo);
echo "=====response=====\r\n";
print_r($response);
}
curl_close($ci);
return $response;
}
}
```
## 獲取當前日期是星期幾
```php
if (!function_exists('getTimeWeek'))
{
/**
* 獲取當前時間是星期幾
* @param $time [當前時間戳]
* @param int $i [第幾天之后 默認為0為今天]
* @return mixed
*/
function getTimeWeek($time, $i = 0)
{
$weekArray = [7, 1, 2, 3, 4, 5, 6];
$oneDay = 24 * 60 * 60;
return $weekArray[date('w', $time + $oneDay * $i)];
}
}
```
- PHP獲取客戶端瀏覽器信息和版本
- PHP獲取客戶端操作系統信息
- 無限級分類
- git使用
- 權限檢測思路
- Vue學習
- 遇到的一些問題
- PHP的編碼思維和技巧
- mysql復習
- tp5
- ThinkPHP5.x 公共函數
- TP5登錄注冊
- TP5使用模板繼承
- ThinkPHP5.1 清除緩存
- thinkphp5實現安裝程序
- 安全
- tp中實現跨域代碼
- ThinkPHP5.1配合pjax實現菜單欄無刷新跳轉
- 獲取數據庫版本和數據庫大小
- 模型的基本CURD操作
- 商品spu
- 全局異常處理類
- ExceptionHandler
- BaseException
- PHP函數之error_reporting(E_ALL ^ E_NOTICE)詳細說明
- 微信小程序
- wx:for
- tp6
- 分離的一些模塊
- session開啟
- Spring
- 依賴注入
- 數據結構
- 二叉樹
- js獲取地址欄變量
- PHP設計模式
- 面向對象
- PHP1
- PHP性能優化
- Java學習
- static關鍵字
- 多態
- 接口、階乘
- 大佬給的面試題
- 訪問量為5000萬的博客系統設計
- PHP可變參數
- Nginx的配置案例
- 求數組中的最大值,并返回數組索引
- PHP面試方向
- PHP數組工具類ArrUtil
- 字符串工具類StrUtil
- PHP使用curl發送請求
- mysql
- PHP上傳base64圖片處理函數
- webstorm小程序常用配置
- 郵箱正則表達式
- leetcode mysql記錄
- 函數庫