Home Backend Development PHP Tutorial php curl batch control concurrent asynchronous operations

php curl batch control concurrent asynchronous operations

May 11, 2018 pm 03:47 PM
curl php asynchronous

This time I will bring you php curl batch control concurrent asynchronous operations. What are the precautions for php curl batch control concurrent asynchronous operations? The following is a practical case, let's take a look.

Usually cURL in PHP runs in a blocking manner, which means that after creating a cURL request, you must wait until it executes successfully or times out before executing the next request: CURL is generally preferred for API interface access

In the process of actual projects or writing your own gadgets (such as news aggregation, commodity price monitoring, price comparison), you usually need to obtain data from a third-party website or API interface. When you need to process a URL queue, in order to improve performance , you can use the curl_multi_* family of functions provided by cURL to achieve simple concurrency.

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

<?php

include &#39;curl.class.php&#39;;

function callback($response, $info, $error, $request)

{

 echo &#39;response:<br>';

 print_r($response);

 echo '<br>' date("Y-m-d H:i:s") . '   <br>';

 echo '<br>' str_repeat("-", 100) . '<br>';

}

$USER_COOKIE = (!empty($_REQUEST['cookie'])) ? $_REQUEST['cookie'] : file_get_contents("cookie.txt");

$curl new Curl ("callback");

$data array(

 array(

  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=qmr&type=rec_gametime&referfrom=&rt=0.42521539455332336', //秦美人

  'method' => 'POST',

  'post_data' => '',

  'header' => null,

  'options' => array(

   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=qmr&fenQuNum=3",

   CURLOPT_COOKIE => $USER_COOKIE,

  )

 ),

 array(

  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=sq&type=rec_gametime&referfrom=&rt=0.42521539455332336', //神曲

  'method' => 'POST',

  'post_data' => '',

  'header' => null,

  'options' => array(

   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=sq&fenQuNum=41",

   CURLOPT_COOKIE => $USER_COOKIE,

  )

 ),

 array(

  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=frxz&type=rec_gametime&referfrom=&rt=0.42521539455332336', //凡人修真

  'method' => 'POST',

  'post_data' => '',

  'header' => null,

  'options' => array(

   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=frxz&fenQuNum=3",

   CURLOPT_COOKIE => $USER_COOKIE,

  )

 ),

 array(

  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=smxj&type=rec_gametime&referfrom=&rt=0.42521539455332336', //神魔仙界

  'method' => 'POST',

  'post_data' => '',

  'header' => null,

  'options' => array(

   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=smxj&fenQuNum=2",

   CURLOPT_COOKIE => $USER_COOKIE,

  )

 ),

 array(

  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=qsqy&type=rec_gametime&referfrom=&rt=0.42521539455332336', //倾世情缘

  'method' => 'POST',

  'post_data' => '',

  'header' => null,

  'options' => array(

   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=qsqy&fenQuNum=11",

   CURLOPT_COOKIE => $USER_COOKIE,

  )

 ),

);

foreach ($data as $val) {

 $request new Curl_request ($val ['url'], $val ['method'], $val ['post_data'], $val ['header'], $val ['options']);

 $curl->add($request);

}

$curl->execute();

echo $curl->display_errors();

Copy after login

The effect is very good, no side effects, the number of concurrency is controllable, there are many applications, use your imagination Bar

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

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

<?php

/**

 * cURL批量处理 工具类

 *

 * @since Version 1.0

 * @author Justmepzy <justmepzy@gmail.com>

 * @link http://t.qq.com/JustPzy

 */

/**

 *单一的请求对象

 */

class Curl_request {

 public $url   '';

 public $method   'GET';

 public $post_data  = null;

 public $headers  = null;

 public $options  = null;

 /**

  

  * @param string $url

  * @param string $method

  * @param string $post_data

  * @param string $headers

  * @param array $options

  * @return void

  */

 public function construct($url$method 'GET'$post_data = null, $headers = null, $options = null) {

  $this->url = $url;

  $this->method = strtoupper$method );

  $this->post_data = $post_data;

  $this->headers = $headers;

  $this->options = $options;

 }

 /**

  * @return void

  */

 public function destruct() {

  unset ( $this->url, $this->method, $this->post_data, $this->headers, $this->options );

 }

}

/**

 * 包含请求列队处理

 */

class Curl {

 /**

  * 请求url个数

  * @var int

  */

 private $size    = 5;

 /**

  * 等待所有cURL批处理中的活动连接等待响应时间

  * @var int

  */

 private $timeout   = 5;

 /**

  * 完成请求回调函数

  * @var string

  */

 private $callback   = null;

 /**

  * cRUL配置

  * @var array

  */

 private $options   array (CURLOPT_SSL_VERIFYPEER => 0,CURLOPT_RETURNTRANSFER => 1,CURLOPT_CONNECTTIMEOUT => 30 );

 /**

  * 请求头

  * @var array

  */

 private $headers   array ();

 /**

  * 请求列队

  * @var array

  */

 private $requests   array ();

 /**

  * 请求列队索引

  * @var array

  */

 private $request_map  array ();

 /**

  * 错误

  * @var array

  */

 private $errors   array ();

 /**

  * @access public

  * @param string $callback 回调函数

  * 该函数有4个参数($response,$info,$error,$request)

  * $response url返回的body

  * $info  cURL连接资源句柄的信息

  * $error  错误

  * $request  请求对象

  */

 public function construct($callback = null) {

  $this->callback = $callback;

 }

 /**

  * 添加一个请求对象到列队

  * @access public

  * @param object $request

  * @return boolean

  */

 public function add($request) {

  $this->requests [] = $request;

  return TRUE;

 }

 /**

  * 创建一个请求对象并添加到列队

  * @access public

  * @param string $url

  * @param string $method

  * @param string $post_data

  * @param string $headers

  * @param array $options

  * @return boolean

  */

 public function request($url$method 'GET'$post_data = null, $headers = null, $options = null) {

  $this->requests [] = new Curl_request ( $url$method$post_data$headers$options );

  return TRUE;

 }

 /**

  * 创建GET请求对象

  * @access public

  * @param string $url

  * @param string $headers

  * @param array $options

  * @return boolean

  */

 public function get($url$headers = null, $options = null) {

  return $this->request ( $url"GET", null, $headers$options );

 }

 /**

  * 创建一个POST请求对象

  * @access public

  * @param string $url

  * @param string $post_data

  * @param string $headers

  * @param array $options

  * @return boolean

  */

 public function post($url$post_data = null, $headers = null, $options = null) {

  return $this->request ( $url"POST"$post_data$headers$options );

 }

 /**

  * 执行cURL

  * @access public

  * @param int $size 最大连接数

  * @return Ambigous <boolean, mixed>|boolean

  */

 public function execute($size = null) {

  if (sizeof ( $this->requests ) == 1) {

   return $this->single_curl ();

  else {

   return $this->rolling_curl ( $size );

  }

 }

 /**

  * 单个url请求

  * @access private

  * @return mixed|boolean

  */

 private function single_curl() {

  $ch = curl_init ();

  $request array_shift $this->requests );

  $options $this->get_options ( $request );

  curl_setopt_array ( $ch$options );

  $output = curl_exec ( $ch );

  $info = curl_getinfo ( $ch );

  // it's not neccesary to set a callback for one-off requests

  if ($this->callback) {

   $callback $this->callback;

   if (is_callable $this->callback )) {

    call_user_func ( $callback$output$info$request );

   }

  else

   return $output;

  return true;

 }

 /**

  * 多个url请求

  * @access private

  * @param int $size 最大连接数

  * @return boolean

  */

 private function rolling_curl($size = null) {

  if ($size)

   $this->size = $size;

  else 

   $this->size = count($this->requests);

  if (sizeof ( $this->requests ) < $this->size)

   $this->size = sizeof ( $this->requests );

  if ($this->size < 2)

   $this->set_error ( 'size must be greater than 1' );

  $master = curl_multi_init ();

  //添加cURL连接资源句柄到map索引

  for($i = 0; $i < $this->size; $i ++) {

   $ch = curl_init ();

   $options $this->get_options ( $this->requests [$i] );

   curl_setopt_array ( $ch$options );

   curl_multi_add_handle ( $master$ch );

   $key = ( string ) $ch;

   $this->request_map [$key] = $i;

  }

  $active $done = null;

  do {

   while ( ($execrun = curl_multi_exec ( $master$active )) == CURLM_CALL_MULTI_PERFORM )

    ;

   if ($execrun != CURLM_OK)

    break;

   //有一个请求完成则回调

   while $done = curl_multi_info_read ( $master ) ) {

    //$done 完成的请求句柄

    $info = curl_getinfo ( $done ['handle'] );//

    $output = curl_multi_getcontent ( $done ['handle'] );//

    $error = curl_error ( $done ['handle'] );//

    $this->set_error ( $error );

    //调用回调函数,如果存在的话

    $callback $this->callback;

    if (is_callable $callback )) {

     $key = ( string ) $done ['handle'];

     $request $this->requests [$this->request_map [$key]];

     unset ( $this->request_map [$key] );

     call_user_func ( $callback$output$info$error$request );

    }

    curl_close ( $done ['handle'] );

    //从列队中移除已经完成的request

    curl_multi_remove_handle ( $master$done ['handle'] );

   }

   //等待所有cURL批处理中的活动连接

   if ($active)

    curl_multi_select ( $master$this->timeout );

  while $active );

  //完成关闭

  curl_multi_close ( $master );

  return true;

 }

 /**

  * 获取没得请求对象的cURL配置

  * @access private

  * @param object $request

  * @return array

  */

 private function get_options($request) {

  $options $this->get ( 'options' );

  if (ini_get 'safe_mode' ) == 'Off' || ! ini_get 'safe_mode' )) {

   $options [CURLOPT_FOLLOWLOCATION] = 1;

   $options [CURLOPT_MAXREDIRS] = 5;

  }

  $headers $this->get ( 'headers' );

  if ($request->options) {

   $options $request->options + $options;

  }

  $options [CURLOPT_URL] = $request->url;

  if ($request->post_data && strtolower($request->method) == 'post' ) {

   $options [CURLOPT_POST] = 1;

   $options [CURLOPT_POSTFIELDS] = $request->post_data;

  }

  if ($headers) {

   $options [CURLOPT_HEADER] = 0;

   $options [CURLOPT_HTTPHEADER] = $headers;

  }

  return $options;

 }

 /**

  * 设置错误信息

  * @access public

  * @param string $msg

  */

 public function set_error($msg) {

  if (! empty $msg ))

   $this->errors [] = $msg;

 }

 /**

  * 获取错误信息

  * @access public

  * @param string $open

  * @param string $close

  * @return string

  */

 public function display_errors($open '<p>'$close '</p>') {

  $str '';

  foreach $this->errors as $val ) {

   $str .= $open $val $close;

  }

  return $str;

 }

 /**

  * @access public

  * @param string $name

  * @param string $value

  * @return boolean

  */

 public function set($name$value) {

  if ($name == 'options' || $name == 'headers') {

   $this->{$name} = $value $this->{$name};

  else {

   $this->{$name} = $value;

  }

  return TRUE;

 }

 /**

  

  * @param string $name

  * @return mixed

  * @access public

  */

 public function get($name) {

  return (isset ( $this->{$name} )) ? $this->{$name} : null;

 }

 /**

  * @return void

  * @access public

  */

 public function destruct() {

  unset ( $this->size, $this->timeout, $this->callback, $this->options, $this->headers, $this->requests, $this->request_map, $this->errors );

 }

}

// END Curl Class

/* End of file curl.class.php */

Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Implementation code of puppeteer simulated login capture page

Vue data monitoring watch usage instructions

The above is the detailed content of php curl batch control concurrent asynchronous operations. 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

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 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.

See all articles