~~~
<?php
/**
* =======================================
* Created by Zhihua_W.
* Author: Zhihua_W
* Date: 2016/12/1 0004
* Time: 下午 5:15
* Project: PHP開發小技巧
* Power: 兩種方法實現獲取隨機字符串
* =======================================
*/
/**
* 方法一:獲取隨機字符串
* @param number $length 長度
* @param string $type 類型
* @param number $convert 轉換大小寫
* @return string 隨機字符串
*/
function random($length = 6, $type = 'string', $convert = 0)
{
$config = array(
'number' => '1234567890',
'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
);
if (!isset($config[$type]))
$type = 'string';
$string = $config[$type];
$code = '';
$strlen = strlen($string) - 1;
for ($i = 0; $i < $length; $i++) {
$code .= $string{mt_rand(0, $strlen)};
}
if (!empty($convert)) {
$code = ($convert > 0) ? strtoupper($code) : strtolower($code);
}
return $code;
}
/**
* 方法二:獲取隨機字符串
* @param int $randLength 長度
* @param int $addtime 是否加入當前時間戳
* @param int $includenumber 是否包含數字
* @return string
*/
function rand_str($randLength = 6, $addtime = 1, $includenumber = 0)
{
if ($includenumber) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
} else {
$chars = 'abcdefghijklmnopqrstuvwxyz';
}
$len = strlen($chars);
$randStr = '';
for ($i = 0; $i < $randLength; $i++) {
$randStr .= $chars[rand(0, $len - 1)];
}
$tokenvalue = $randStr;
if ($addtime) {
$tokenvalue = $randStr . time();
}
return $tokenvalue;
}
//其中也可以放多個參數
//random(4,'number');
//random(6,'letter',1);
echo random(10);
//方法二同樣
echo rand_str(6);
?>
~~~
- 目錄
- Array
- array_column()
- 數組和變量
- compact() 函數
- extract() 函數
- Url
- base64_encode — 使用 MIME base64 對數據進行編碼
- 圖像
- getimagesize()
- 隨機數
- getrandmax
- mt_getrandmax
- mt_rand
- rand
- empty函數
- exec()函數
- 權限修改
- 可變函數
- 函數閉包
- 報警級別
- 持續函數
- 自定義
- 字符處理
- 中文首字母
- 隨機字符串
- url函數
- parse_url_param
- 頁面采集
- 簡單采集
- Referer采集
- CURL
- 發送json數據
- Curl多線程
- 文件處理
- 遞歸刪除
- 圖片顯示
- 類方法
- 保留字
- 檢查類文件名稱
- Cookie
- 數組
- 數學函數
- 第三方函數庫
- 精度計算
- BC Math
- 計算執行時間
- 日期時間
- 時間戳
- header
- 調試函數
- get_class
- get_class_methods
- 數組函數
- array_intersect_key()
- 二維數組
- Base64編碼
- URL安全
- 加密擴展
- Hash函數
- hash_file
- hash_hmac
- hash_algos
- 文件讀寫
- is_writable()
- file_put_contents()