php一些工具函數介紹

來源:互聯網
上載者:User
本文主要和大家分享php一些工具函數介紹,這些都是比較常用的工具函數,希望能協助到大家。

1.獲得毫秒層級的時間戳記

    public static function get_millisecond()    {        //擷取毫秒的時間戳記        $time = explode(" ", microtime());        $time = $time[1] . substr($time[0], 2, 3);        return $time;    }

2讀取檔案內容

    public static function file_read($file_path)    {        if (file_exists($file_path)) {            $fp = fopen($file_path, "r");            $str = fread($fp, filesize($file_path));//指定讀取大小,這裡把整個檔案內容讀取出來            $str = str_replace("\r\n", "<br />", $str);            fclose($fp);            return $str;        } else {            return false;        }    }

3產生隨機字串,不長於32位

    public static function get_nonce_number($length = 11)    {        $chars = "0123456789";        $str = "";        for ($i = 0; $i < $length; $i++) {            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);        }        return $str;    }

4.產生訂單詳情號 預設為16位

    public static function get_order_id($length = 16)    {        //見方法一,獲得毫秒層級時間戳記        $time = self::get_millisecond();        $len = $length - 13;        $str = self::get_nonce_number($len);        if (strlen($time) != 13) {            $orderId = $str . $time . rand(1, 9);        } else {            $orderId = $str . $time;        }        return $orderId;    }

5.隨機產生字母和數字(有重複的可能性)

    public static function randomkeys($length)    {        $returnStr = '';        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';        for ($i = 0; $i < $length; $i++) {            $returnStr .= $pattern{mt_rand(0, 61)}; //產生php隨機數        }        return $returnStr;    }

6.產生6位元驗證碼

    public static function random_code($length = 6)    {        $code = rand(pow(10, ($length - 1)), pow(10, $length) - 1);        return "$code";    }

7.防sql注入,xss攻擊

    public static function clean($str)    {        $str = trim($str);        $str = strip_tags($str);        $str = stripslashes($str);        $str = addslashes($str);        $str = rawurldecode($str);        $str = quotemeta($str);        $str = htmlspecialchars($str);        return $str;    }

8.接收post或者get參數

    public static function get_input($name)    {        $request = Yii::$app->request;        if (isset($_GET[$name])) {            $value = $request->get($name);        } elseif (isset($_POST[$name])) {            $value = $request->post($name);        } else {            $value = '';        }        return $value;    }

9.加密方法

    public static function aes_encrypt($str)    {        $privateKey = "私密金鑰檔案字串";        $iv = "公開金鑰檔案字串";        //加密        $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $str, MCRYPT_MODE_CBC, $iv);//        return urlencode(base64_encode($encrypted));        return base64_encode($encrypted);    }

10.解密方法

    public static function aes_decrypt($str)    {        $privateKey = "私密金鑰檔案字串";        $iv = "公開金鑰檔案字串";        $encryptedData = base64_decode($str);        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateKey, $encryptedData, MCRYPT_MODE_CBC, $iv);        $decrypted = rtrim($decrypted, "\0");        return $decrypted;    }

11.curl類比帶header頭資訊的get請求

    public static function curl_get($request_url,$session=[])    {        if($session){            $ch = curl_init();            $header = ["session:".$session]; //設定一個你的瀏覽器agent的header            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);            curl_setopt($ch, CURLOPT_HEADER, 0); //返回response頭部資訊            curl_setopt($ch, CURLOPT_URL, $request_url);            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不在頁面輸出  返回資料            $data_json=curl_exec($ch);            curl_close($ch);        }else{            $curl = new Curl();            $data_json = $curl->get($request_url);        }        $data = json_decode($data_json, true);        return $data;    }

12.curl類比帶header頭資訊的post方法

    public static function curl_post($request_url,$params,$session=""){        if($session){            $curl = curl_init();  //初始化            $header = ["session:".$session]; //設定一個你的瀏覽器agent的header            curl_setopt($curl,CURLOPT_URL,$request_url);  //設定url//            curl_setopt($curl,CURLOPT_HTTPAUTH,CURLAUTH_BASIC);  //設定http驗證方法            curl_setopt($curl,CURLOPT_HTTPHEADER,$header);  //設定頭資訊            curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);  //設定curl_exec擷取的資訊的返回方式            curl_setopt($curl,CURLOPT_POST,1);  //設定發送方式為post請求            curl_setopt($curl,CURLOPT_POSTFIELDS,$params);  //設定post的資料            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//不在頁面輸出  返回資料            $data_json = curl_exec($curl);            if($data_json === false){                echo curl_errno($curl);                exit();            }            curl_close($curl);        }else{            $curl = new Curl();            $data_json = $curl->setOption(CURLOPT_POSTFIELDS, http_build_query($params))->post($request_url);        }        $data = json_decode($data_json, true);        return $data;    }

13.遠程下載圖片到本地

    public static function downloadImage($url, $user_token)    {        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        $file = curl_exec($ch);        curl_close($ch);        $filename=$user_token.".jpg";        $path="./images/user/".$filename;        self::saveAsImage($file, $path);    }    private  static function saveAsImage($file, $path)    {        $resource = fopen($path, 'a');        fwrite($resource, $file);        fclose($resource);    }

14.七牛上傳圖片

    public static function  actionImg($filename,$filepath)    {        $auth = new Auth(trim(Yii::$app->params["qiniu_params"]["accessKey"]),            trim(Yii::$app->params["qiniu_params"]["secretKey"]));        $uploadMgr = new UploadManager();        $token = $auth->uploadToken(trim(Yii::$app->params["qiniu_params"]["upload_path"]));        list($succ, $fail) = $uploadMgr->putFile($token,            $filename,            $filepath        );        $url = Yii::$app->params["qiniu_params"]["picture_url"] . "/" . $succ["key"];        return $url;    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.