Home Backend Development PHP Tutorial Introduction to the calling interface and common functions of PHP encapsulated curl

Introduction to the calling interface and common functions of PHP encapsulated curl

Jul 03, 2018 pm 03:52 PM
curl php

今天为大家分享一篇PHP封装curl的调用接口及常用函数详解,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧

如下所示:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

<?php

    /**

     * @desc 封装curl的调用接口,post的请求方式

     */

    function doCurlPostRequest($url, $requestString, $timeout = 5) {

        if($url == "" || $requestString == "" || $timeout <= 0){

            return false;

        }

         $con = curl_init((string)$url);

     curl_setopt($con, CURLOPT_HEADER, false);

     curl_setopt($con, CURLOPT_POSTFIELDS, $requestString);

     curl_setopt($con, CURLOPT_POST, true);

     curl_setopt($con, CURLOPT_RETURNTRANSFER,true);

     curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);

        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, false);

     return curl_exec($con);

    }

     

    /**

     * @desc 封装curl的调用接口,post的请求方式

     */

    function doCurlPostsslRequest($url, $requestString,$pemfile, $timeout = 5) {

        if($url == "" || $requestString == "" || $timeout <= 0){

            return false;

        }

         

        echo $pemfile;

         $con = curl_init((string)$url);

     curl_setopt($con, CURLOPT_HEADER, false);

     curl_setopt($con, CURLOPT_POSTFIELDS, $requestString);

     curl_setopt($con, CURLOPT_POST, true);

     curl_setopt($con, CURLOPT_RETURNTRANSFER,true);

     curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);

        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, 1);

        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, 2);

        //curl_setopt($ch, CURLOPT_SSLCERT, $pemfile);

        //curl_setopt($ch, CURLOPT_SSLCERTTYPE, &#39;PEM&#39;);

        curl_setopt($con, CURLOPT_CAINFO, $pemfile);

     return curl_exec($con);

    }

    /**

     * @desc 封装curl的调用接口,post Json数据的请求方式

     */

    function doCurlPostJsonReq($url, $requestString, $timeout = 25){

        if($url == "" || $requestString == "" || $timeout <= 0){

            return false;

        }

     $con = curl_init((string)$url);

     curl_setopt($con, CURLOPT_HEADER, false);

     curl_setopt($con, CURLOPT_POSTFIELDS, $requestString);

     curl_setopt($con, CURLOPT_POST, true);

     curl_setopt($con, CURLOPT_RETURNTRANSFER,true);

     curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);

        curl_setopt($con, CURLOPT_HTTPHEADER, array(

            &#39;Content-Type: application/json&#39;,

            &#39;Content-Length: &#39; . strlen($data_string))

        );

     return curl_exec($con);

    }

    /**

     * @desc 封装curl的调用接口,post form数据的请求方式

     */

    function doCurlPostFormReq($url, $requestString, $timeout = 25){

        if($url == "" || $requestString == "" || $timeout <= 0){

            return false;

        }

     $con = curl_init((string)$url);

     curl_setopt($con, CURLOPT_HEADER, false);

     curl_setopt($con, CURLOPT_POSTFIELDS, $requestString);

     curl_setopt($con, CURLOPT_POST, true);

     curl_setopt($con, CURLOPT_RETURNTRANSFER,true);

     curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);

        curl_setopt($con, CURLOPT_HTTPHEADER, array(

            &#39;Content-Type: application/x-www-form-urlencoded&#39;)

        );

     return curl_exec($con);

    }

    /**

     * @desc 封装curl的调用接口,get的请求方式

     */

    function doCurlGetRequest($url, $data = array(), $timeout = 10) {

        if($url == "" || $timeout <= 0){

            return false;

        }

        if($data != array()) {

            $url = $url . &#39;?&#39; . http_build_query($data);

        }

        Log::write("发送URL[".$url."]");

        $con = curl_init((string)$url);

        curl_setopt($con, CURLOPT_HEADER, false);

        curl_setopt($con, CURLOPT_RETURNTRANSFER,true);

        curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);

        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, false);

        return curl_exec($con);

    }

    /**

     *截取字符串,中文无乱码

    */

    function msubstr($str, $start=0, $length=0,$suffix=false,$charset="utf-8"){

     if(mb_strlen($str,"UTF8") >= $length){

      $next_str = "…";

     }else{

      $next_str = "";

     }

     if(function_exists("mb_substr")){

      if($suffix)

       // return mb_substr($str, $start, $length, $charset)."…";

       return mb_substr($str, $start, $length, $charset).$next_str;

      else

       return mb_substr($str, $start, $length, $charset);

     }elseif(function_exists(&#39;iconv_substr&#39;)) {

      if($suffix)

       // return iconv_substr($str,$start,$length,$charset)."…";

       return iconv_substr($str,$start,$length,$charset).$next_str;

      else

       return iconv_substr($str,$start,$length,$charset);

     }

     $re[&#39;utf-8&#39;] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";

     $re[&#39;gb2312&#39;] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";

     $re[&#39;gbk&#39;] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";

     $re[&#39;big5&#39;] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";

     preg_match_all($re[$charset], $str, $match);

     $slice = join("",array_slice($match[0], $start, $length));

      if($suffix) return $slice."…";

     if(!$suffix) return $slice;

     return $slice;

    }

    /**

     *用户名*隐藏

     *$str = "如来神掌";

     *echo cut_str($str, 1, 0).&#39;**&#39;.cut_str($str, 1, -1);

     *输出:如**掌

    */

    function cut_str($string, $sublen, $start = 0, $code = &#39;UTF-8&#39;)

    {

     if($code == &#39;UTF-8&#39;)

     {

      $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(&#39;&#39;, array_slice($t_string[0], $start, $sublen));

      return join(&#39;&#39;, array_slice($t_string[0], $start, $sublen));

     }

     else

     {

      $start = $start*2;

      $sublen = $sublen*2;

      $strlen = strlen($string);

      $tmpstr = &#39;&#39;;

      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;

     }

    }

    /*

    *解决json_encode转换中文的问题,在php5.4下json_encode本身解决的这个问题

    */

    function unescapedUnicode($match)

    {

        return mb_convert_encoding(pack(&#39;H*&#39;, $match[1]), &#39;UTF-8&#39;, &#39;UCS-2BE&#39;);

    }

    /**

    *截取手机号

    *demo:13112345678

    *return:131****5678

    */

    function hidtel($phone){

     $IsWhat = preg_match(&#39;/(0[0-9]{2,3}[-]?[2-9][0-9]{6,7}[-]?[0-9]?)/i&#39;,$phone); //固定电话

     if($IsWhat == 1){

      return preg_replace(&#39;/(0[0-9]{2,3}[-]?[2-9])[0-9]{3,4}([0-9]{3}[-]?[0-9]?)/i&#39;,&#39;$1****$2&#39;,$phone);

     }else{

      return preg_replace(&#39;/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i&#39;,&#39;$1****$2&#39;,$phone);

     }

    }

    //获取IP

    function getIp()

    {

        if (isset($_SERVER)){

            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){

                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];

            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {

                $realip = $_SERVER["HTTP_CLIENT_IP"];

            } else {

                $realip = $_SERVER["REMOTE_ADDR"];

            }

        } else {

            if (getenv("HTTP_X_FORWARDED_FOR")){

                $realip = getenv("HTTP_X_FORWARDED_FOR");

            } else if (getenv("HTTP_CLIENT_IP")) {

                $realip = getenv("HTTP_CLIENT_IP");

            } else {

                $realip = getenv("REMOTE_ADDR");

            }

        }

     

        return $realip;

    }

    //把汉字转换为数字

    function getUnicodeFromOneUTF8($word)

    {

        //获取其字符的内部数组表示,所以本文件应用utf-8编码!

        //$word = iconv("gb2312", "utf-8", $word);

        if (is_array($word))

            $arr = $word;

        else

            $arr = str_split($word);

        //此时,$arr应类似array(228, 189, 160)

        //定义一个空字符串存储

        $bin_str = &#39;&#39;;

        //转成数字再转成二进制字符串,最后联合起来。

        foreach ($arr as $value)

            $bin_str .= decbin(ord($value));

        //此时,$bin_str应类似111001001011110110100000

        //正则截取

        $bin_str = preg_replace(&#39;/^.{4}(.{4}).{2}(.{6}).{2}(.{6})$/&#39;,&#39;$1$2$3&#39;, $bin_str);

        //此时, $bin_str应类似0100111101100000,如果是汉字"你"

        return bindec($bin_str);

        //返回类似20320, 汉字"你"

        //return dechex(bindec($bin_str));

        //如想返回十六进制4f60,用这句

Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

PHP取整函数:ceil,floor,round,intval的区别介绍

关于php htmlentities()函数的定义和用法

关于PHP zip压缩包操作类的介绍

The above is the detailed content of Introduction to the calling interface and common functions of PHP encapsulated curl. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles