整理收藏常用方法大全,欢迎大家补充(PHP)
1、生成32位唯一ID
/**
* 生成唯一id[32位]
*
* @param string $namespace
* @return string
*/
public static function createUniqid($namespace = ''){
static $uniqid = '';
$uid = uniqid("", true);
$data = $namespace;
$data .= isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : "";
$data .= isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
$data .= isset($_SERVER['LOCAL_ADDR']) ? $_SERVER['LOCAL_ADDR'] : "";
$data .= isset($_SERVER['LOCAL_PORT']) ? $_SERVER['LOCAL_PORT'] : "";
$data .= isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : "";
$data .= isset($_SERVER['REMOTE_PORT']) ? $_SERVER['REMOTE_PORT'] : "";
$hash = strtoupper(hash('ripemd128', $uid . $uniqid . md5($data)));
$uniqid = substr($hash, 0, 8) . substr($hash, 8, 4) . substr($hash, 12, 4) . substr($hash, 16, 4) . substr($hash, 20, 12);
return $uniqid;
}
2、生成毫秒时间戳
/**
* 获取当前时间的毫秒数
*
* @return float
*/
public static function getMicroTime(){
list($t1, $t2) = explode(' ', microtime());
return (float)sprintf('%.0f'(floatval($t1)+floatval($t2))*1000);
}
3、生成hmac_sha1加密
/**
* 生成sig
*
* @param type $data
* @return string sig
*/
private function _generateSig($data) {
//拼接编码
$paramString = base64_encode($this->_genQueryString($data));
//key
$key = $this->appSecret . $this->serverAuthStaticKey;
//sha1 加密
$sha1Key = hash_hmac("sha1", $paramString, $key, true);
//返回sig
return md5($sha1Key);
}
/**
* 生成查询字符串
*
* @param type $data 查询数据
* @return string 查询字符串
*/
private function _genQueryString($data) {
//删除sig
$temp = [];
foreach ($data as $key => $value) {
$temp[] = $key . "=" . $value;
}
return implode("&", $temp);
}
4、生成唯一字符串
$uniqidStr = sha1(uniqid('', TRUE) . mt_rand());
5、短信CURL获取内容信息
/**
* PHP发送Json对象数据, 发送HTTP请求
*
* @param string $url 请求地址
* @param array $data 发送数据
* @return String
*/
function http_post_json($functionName, $url, $data) {
$ch = curl_init( $url );
// application/x-www-from-urlencoded 类型
curl_setopt( $ch, CURLOPT_POST, 1 );
// 如果你想把一个头包含在输出中,设置这个选项为一个非零值
curl_setopt( $ch, CURLOPT_HEADER, 0 );
// TRUE 强制获取一个新的连接,而不是缓存中的连接
curl_setopt( $ch, CURLOPT_FRESH_CONNECT, 1 );
// TRUE 将curl_exec()获取的信息以字符串返回,而不是直接输出
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
// TRUE 在完成交互以后强制明确的断开连接,不能在连接池中重用
curl_setopt( $ch, CURLOPT_FORBID_REUSE, 1 );
// 设置一个长整形数,作为最大延续多少秒
curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
// 设置 HTTP 头字段的数组。格式: array('Content-type: text/plain', 'Content-length: 100')
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen( $data ) ) );
// 传递一个作为HTTP “POST”操作的所有数据的字符串
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );
// 抓取URL并把它传递给浏览器
$ret = curl_exec( $ch );
echo $functionName . " : Request Info : url: " . $url . " ,send data: " . $data . " \n";
echo $functionName . " : Respnse Info : " . $ret . " \n";
// 关闭cURL资源,并且释放系统资源
curl_close( $ch );
return $ret;
}