开发者

CURL - Problem with Authentication

开发者 https://www.devze.com 2022-12-25 17:36 出处:网络
I need to add authentication to this function: function multiRequest($data, $options = array()) { // array of curl handles

I need to add authentication to this function:

function multiRequest($data, $options = array()) {

  // array of curl handles
  $curly = array();
  // data to be returned
  $result = array();

  // multi handle
  $mh = curl_multi_init();

  // loop through $data and create curl handles
  // then add them to the multi-handle
  foreach ($data as $id => $d) {

    $curly[$id] = curl_init();

    $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
    curl_setopt($curly[$id], CURLOPT_URL,            $url);
    curl_setopt($curly[$id], CURLOPT_HEADER,         0);
    curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);

    // post?
    if (is_array($d)) {
      if (!empty($d['p开发者_运维百科ost'])) {
        curl_setopt($curly[$id], CURLOPT_POST,       1);
        curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
      }
    }

    // extra options?
    if (!empty($options)) {
      curl_setopt_array($curly[$id], $options);
    }

    curl_multi_add_handle($mh, $curly[$id]);
  }

  // execute the handles
  $running = null;
  do {
    curl_multi_exec($mh, $running);
  } while($running > 0);

  // get content and remove handles
  foreach($curly as $id => $c) {
    $result[$id] = curl_multi_getcontent($c);
    curl_multi_remove_handle($mh, $c);
  }

  // all done
  curl_multi_close($mh);

  return $result;
}

I'm looking to add authentication to this function, something along these lines?

curl_setopt($curly[$id], CURLOPT_USERPWD, "$username:$password");

Anyone help?


Have you tried the code you posted? That looks good to me:

curl_setopt($curly[$id], CURLOPT_USERPWD, "$username:$password");

But this function already works with auth, just pass the auth string "user:pass" in the $options array.

multiRequest($data, array('CURLOPT_USERPWD' => "user:pass"));

If you're looking to set auth for each curl handle, something like this should work:

// auth?
if (is_array($d)) {
  if (!empty($d['user']) AND !empty($d['pass']) {
    curl_setopt($curly[$id], CURLOPT_USERPWD, "{$d['user']}:{$d['pass']}");
  }
}

Then just pass 'user' and 'auth' elements as part of the multidimensional array.


Can the function definition be changed?

function multiRequest($data,$user,$pwd, $options = array())

Then in the foreach loop, do the following:

...
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curly[$id], CURLOPT_USERPWD, "$user:$pwd");

// post?
...
0

精彩评论

暂无评论...
验证码 换一张
取 消