Combine 2 associative arrays - php

I have 2 arrays that i have created from 2 different systems:
URL changed
I need to loop through the array on the left and find a match for the business, address and zip. If there is a match on the right side then I need to grab the id and add it to the array item on the left.
I am structuring the arrays so i can change them as needed.
${'URL'} = 'http://reviewsfor.biz/api/biz/';
// Initiate the cURL request
$curl = curl_init();
$data = array(
'api_key' => REVIEWS_API_KEY,
'format' => 'json',
'act' => 'active'
);
// Set the cURL options
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
curl_setopt($curl, CURLOPT_URL, ${'URL'}.'?'.http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Execute the cURL POST
$response = curl_exec($curl);
// Close the cURL connection
curl_close($curl);
$response = json_decode($response);
// Out the list of businesses into an array
${'Business List'} = $response->businesses;
${'Local Biz Array'} = array();
${'Query'} = mysql_query('SELECT * FROM `companies`.`subdomains`');
while(${'Sub Domain'} = mysql_fetch_assoc(${'Query'})){
${'Database'} = ${'Sub Domain'}['database'];
${'DB Query'} = mysql_query('SELECT * FROM `'.${'Database'}.'`.`users`');
while(${'User'} = mysql_fetch_assoc(${'DB Query'})){
if(${'User'}['company'] != ''){
${'Local Biz Array'}[] = array('business' => ${'User'}['company'], 'address' => ${'User'}['company_address'], 'zip' => ${'User'}['company_zip'], 'user_id' => ${'User'}['id']);
}
}
}
// Build an array
${'LBL Biz Array'} = array();
foreach(${'Business List'} as $item){
${'LBL Biz Array'}[] = array('business' => $item->business->business, 'address' => $item->business->address, 'zip' => $item->business->zip, 'id' => $item->business->id);
}
echo '<div id="leftCol" style="float:left;width:49%;height:500px;overflow:scroll;">';
echo '<pre>';
print_r(${'LBL Biz Array'});
echo '</pre></div>';
echo '<div id="rightCol" style="float:right;width:49%;height:500px;overflow:scroll;">';
echo '<pre>';
print_r(${'Local Biz Array'});
echo '</pre></div>';

function findMatch($arrayLeft, $arrayRight){
for($i=0,$j=count($arrayLeft);$i<$j;$i++){
for($k=0,$l=count($arrayRight);$k<$l; $k++){
if($arrayLeft[$i]['business'] == $arrayRight[$k]['business'] && $arrayLeft[$i]['address'] == $arrayRight[$k]['address'] && $arrayLeft[$i]['zip'] == $arrayRight[$k]['zip']){
$arrayLeft[$i]['user_id'] = $arrayRight[$k]['user_id'];
unset($arrayRight[$k]); //remove addresses already matched
break;
}
}
}
return $arrayLeft;
}

Related

kill sessions after payment and return to callback page

after user fill form of his or her information it create some sessions that i need kill all sessions in callback page but it dont work by destroy sessions or unset sessions.
after fill information page we have 3 pages as bellow.
payment.php
<?php session_start();
require_once('variables.php');
require_once('../includes/config.php');
$stmt = $db->prepare('SELECT * FROM order_main WHERE name = :name and phone=:phone');
if($stmt->execute(array(':name' => $_SESSION['post-data']['name'], ':phone' => $_SESSION['post-data']
['phone'] ) ));
while($row = $stmt->fetch()){
//if($code == $row['code']){
//if(!empty($_POST['code'])){
$_SESSION['order_id'] = $row['order_id'];
//}
// }
}
$order_id = $_SESSION['order_id'];
$amount = $_SESSION['total'];
echo $_SESSION['order_id'];
$_SESSION['order_id']=3;
echo $_SESSION['post-data']['name'];
echo $_SESSION['post-data']['order_desc'];
$name = $_SESSION['post-data']['name'];
$phone = $_SESSION['post-data']['phone'];
$order_desc = $_SESSION['post-data']['order_desc'];
$params = array(
'order_id' => $order_id ,
'amount' => 10000,
'phone' => $phone,
'name' => $name,
'desc' => $order_desc,
'callback' => URL_CALLBACK,
);
idpay_payment_create($params);
/**
* #param array $params
* #return bool
*/
function idpay_payment_create($params) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_PAYMENT);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) || empty($result->link)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
//.Redirect to payment form
header('Location:' . $result->link);
}
variables.php
<?php session_start();
define('URL_CALLBACK', 'http://www.siteaddress.org/blog/php-simple-master/callback.php');
define('URL_PAYMENT', 'https://api.idpay.ir/v1.1/payment');
define('URL_INQUIRY', 'https://api.idpay.ir/v1.1/payment/inquiry');
define('URL_VERIFY', 'https://api.idpay.ir/v1.1/payment/verify');
define('APIKEY', 'xxxxx...');
define('SANDBOX', 1);
callback.php(i want destroy some or all sessions here but cant)
<?php session_start();
require_once('variables.php');
require_once('config.php');
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$response = $_POST;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$response = $_GET;
}
if (empty($response['status']) ||
empty($response['id']) ||
empty($response['track_id']) ||
empty($response['order_id'])) {
return FALSE;
}
if ($response['status'] != 10) {
print idpay_payment_get_message($response['status']);
}
// if $response['id'] was not in the database return FALSE
$inquiry = idpay_payment_get_inquiry($response);
if ($inquiry) {
$verify = idpay_payment_verify($response);
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_get_inquiry($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_INQUIRY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
if ($result->status == 10) {
return TRUE;
}
print idpay_payment_get_message($result->status);
return FALSE;
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_verify($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_VERIFY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
print idpay_payment_get_message($result->status);
//print '<pre>';
//print_r($result);
//print '</pre>';
$stmt = $db->prepare('UPDATE order_main SET track_id = :track_id, id = :id, order_date=:date
WHERE order_id = :order_id ') ;
$stmt->execute(array(
':track_id' => $_GET['track_id'],
':id' => $_GET['id'],
':date' => $_GET['date'],
':order_id' => $_GET['order_id']
));
}
/**
* #param int $status
* #return string
*/
function idpay_payment_get_message($status) {
switch ($status) {
case 1:
return 'پرداخت انجام نشده است';
case 2:
return 'پرداخت ناموفق بوده است';
case 3:
return 'خطا رخ داده است';
case 10:
return 'در انتظار تایید پرداخت';
case 100:
return 'پرداخت تایید شده است لطفا منتظر بمانید';
case 101:
return 'پرداخت قبلاً تایید شده است';
default:
return 'Error handeling';
}
}
unset ($_SESSION['post-data']['name']);
unset ($_SESSION['post-data']['phone']);
if($_GET['order_desc']){
unset ($_SESSION['post-data']['order_desc']);
}
unset ($_SESSION['order_id']);
unset ($_SESSION['shopping_cart']);
session_start();
session_destroy();
session_commit();
just add session_destroy($_SESSION["your_session]); at the end of your code and same for session_commit

Error in creating record in zohocrm contacts using php 7.1

I am trying to create a record in zohocrm. i am using API version2 code.
i recieve this following error which i stated below. I tried stackoverflow for solutions but can't find relevant solution. I tried this Stackoverflow answer Zoho API V2 Update Record. It doesn't work for me. Help me with some solution. i use php version
7.1
Here's the Code i used:
public function createRecord($module, $module_fields)
{
global $HelperObj;
$WPCapture_includes_helper_Obj = new WPCapture_includes_helper_PRO();
$activateplugin = $WPCapture_includes_helper_Obj->ActivatedPlugin;
$moduleslug = $this->ModuleSlug = rtrim(strtolower($module), "s");
$zohoapi = new SmackZohoApi();
$module_field['data'] = array($module_fields);
$module_field['Owner']['id'] = $module_fields['SMOWNERID'];
$fields_to_skip = ['Digital_Interaction_s', 'Solution'];
foreach ($module_fields as $fieldname => $fieldvalue) {
if (!in_array($fieldname, $fields_to_skip)) {
continue;
}
$module_fields[$fieldname] = array();
if (is_string($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
} else if (is_array($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
}
}
//$fields = json_encode($module_fields);
$attachments = $module_fields['attachments'];
$body_json = array();
$body_json["data"] = array();
array_push($body_json["data"], $module_fields);
$record = $zohoapi->Zoho_CreateRecord($module, $body_json, $attachments);
if ($record['code'] == 'INVALID_TOKEN' || $record['code'] == 'AUTHENTICATION_FAILURE') {
$get_access_token = $zohoapi->refresh_token();
if (isset($get_access_token['error'])) {
if ($get_access_token['error'] == 'access_denied') {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "Access Denied to get the refresh token";
return $data;
}
}
$exist_config = get_option("wp_wpzohopro_settings");
$config['access_token'] = $get_access_token['access_token'];
$config['api_domain'] = $get_access_token['api_domain'];
$config['key'] = $exist_config['key'];
$config['secret'] = $exist_config['secret'];
$config['callback'] = $exist_config['callback'];
$config['refresh_token'] = $exist_config['refresh_token'];
update_option("wp_wpzohopro_settings", $config);
$this->createRecord($module, $module_fields);
} elseif ($record['data'][0]['code'] == 'SUCCESS') {
$data['result'] = "success";
$data['failure'] = 0;
} else {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "failed adding entry";
}
return $data;
}
API Call Code:
public function Zoho_CreateRecord($module = "Lead",$data_array,$extraParams) {
try{
$apiUrl = "https://www.zohoapis.com/crm/v2/$module";
$fields = json_encode($data_array);
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', $this->access_token),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
curl_close($ch);
$result_array = json_decode($result,true);
if($extraParams != "")
{
foreach($extraParams as $field => $path){
$this->insertattachment($result_array,$path,$module);
}
}
}catch(\Exception $exception){
// TODO - handle the error in log
}
return $result_array;
}
error i got:
Array
(
[data] => Array
(
[0] => Array
(
[code] => INVALID_DATA
[details] => Array
(
[expected_data_type] => jsonarray
[api_name] => Solution_Interest
)
[message] => invalid data
[status] => error
)
)
)
By the details which you gave ,
(1)you said you wish to create "Contacts" , but the url you are using to create contact doesn't seems to create "Contacts" either by
**converting leads to account and contact , or
**directly creating contact
(2)you mentioned module name as "Lead" , try changing it to "Leads".
(3)variables $data_array & $extraParams , doesn't seems to hold any value , they seems to be null.
(4)Here is a help doc. for you
Create Contact
If that still doesn't solve your problem ,you could ask your queries at zoho crm community , people will definitely solve your queries Ask here

Json data get from API URL (using curl)

The online service "eTermin" provides an API Url which outputs reviews of my service.
I tried it with this code but only got a bad request and an error:
$service_url = 'https://www.etermin.net/api/rating/';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false); // DEBUGGING set to true
$curl_response = curl_exec($curl);
echo print_r($curl_response); // test the JSON array
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response, true);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
The eTermin FAQ did not provide all the information needed. In order to GET or POST you need to send a publickey, a salt and an encoded signature in the Header.
So this is the solution to GET the ratings of my eTermin account (the return is not formatted yet!):
$publicKey = "[publicKey]";
$secretKey = "[secretKey]";
// Generates a random string of ten digits
$salt = mt_rand();
// Computes the signature by hashing the salt with the secret key as the key
$signature = hash_hmac('sha256', $salt, $secretKey, true);
// base64 encode
$encodedSignature = base64_encode($signature);
// CURL GET REQUEST
$service_url = 'https://www.etermin.net/api/rating/';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'publickey:'.$publicKey,
'salt:'.$salt,
'signature:'.$encodedSignature
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HEADER, true);
$curl_response = curl_exec($curl);
$curl_response = json_decode($curl_response);
echo print_r($curl_response);
This is what it returns:
Array ( [0] => stdClass Object ( [ID] => 60979 [AppointmentExternalID] => XXXXXXX [CustomerFeedback] => Sehr schöner Laden, sehr privat. Wir wurden von zwei Experten gleichzeitig beraten, Preise sind angemessen. Schöne Anzüge. Wir sind zufrieden. [Rating] => 5 [CustomerInfo] => Benjamin (email#something.at, ) [RatingDate] => 2018-01-24T17:21:20.793 [CalendarID] => 46499 [CalendarName] => Kalender [ServiceID] => 60347 [Publish] => 1 ) [1] => stdClass Object ( [ID] => 61014 [AppointmentExternalID] => XXXXXXXX [CustomerFeedback] => [Rating] => 5 .....
Now all I need to do is format this somehow and get the char encoding to work.
In order to parse the JSON for eTermin ratings use this foreach loop:
//Traverse array __standard_Obj
foreach ($decoded as $key => $value) {
$c_feeback = $value["CustomerFeedback"];
$c_name = $value["CustomerInfo"];
$c_name = before ('(',$c_name);
$c_rating = $value["Rating"];
$c_date = $value["RatingDate"];
if(!empty($c_feeback)):
echo '<h2>Feedback:'.$x.'</h2>';
$x++;
echo '<div>';
if(strlen($c_name)>3):
echo $c_name;
else:
echo "Anonym";
endif;
echo ': '.$c_feeback;
//positiv stars
//$c_rating = 4; //testvalue
for($c = 0; $c < $c_rating; $c++) {
echo '<span class="fa fa-star checked"></span>';
}
//negative stars
$c_rating = 5 - $c_rating;
for($c = 0; $c < $c_rating; $c++) {
echo '<span class="fa fa-star"></span>';
}
endif;
}

PHP Loop Function with different parameters

I have a function which queries an api and outputs the response as an array. I can run this function once and then I can echo the array output.
But problem for me is, I can call this function once and have output. But I'd like to loop through these function parameters and call it for multiple usernames. Example:
<?php
require("./include/function.php");
$Player=fetchCharacterDescriptions("Senaxx", "2");
echo "<tr>";
echo "<th class=\"col-md-3\">" . $Player[0]['username'] . "</th>";
foreach ( $Player as $var )
{
echo "<th class=\"col-md-3\">",$var['class']," ",$var['light'],"</th>";
}
echo "</tr>";
echo "</thead>";
echo "</table>";
?>
And this call's the function fetchCharacterDescriptions in function.php which is:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$hash = array(
'3159615086' => 'Glimmer',
'1415355184' => 'Crucible Marks',
'1415355173' => 'Vanguard Marks',
'898834093' => 'Exo',
'3887404748' => 'Human',
'2803282938' => 'Awoken',
'3111576190' => 'Male',
'2204441813' => 'Female',
'671679327' => 'Hunter',
'3655393761' => 'Titan',
'2271682572' => 'Warlock',
'3871980777' => 'New Monarchy',
'529303302' => 'Cryptarch',
'2161005788' => 'Iron Banner',
'452808717' => 'Queen',
'3233510749' => 'Vanguard',
'1357277120' => 'Crucible',
'2778795080' => 'Dead Orbit',
'1424722124' => 'Future War Cult',
'2033897742' => 'Weekly Vanguard Marks',
'2033897755' => 'Weekly Crucible Marks',
);
function translate($x)
{
global $hash;
return array_key_exists($x, $hash) ? $hash[$x] : null;
}
//BungieURL
function callBungie($uri)
{
$apiKey = '145c4aff30864167ac4548c02c050679';
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-API-Key: ' . $apiKey
));
if (!$result = json_decode(curl_exec($ch) , true))
{
$result = false;
}
curl_close($ch);
return $result;
}
//Request Player
function fetchPlayer($username, $platform)
{
$result = false;
$uri = 'http://www.bungie.net/Platform/Destiny/SearchDestinyPlayer/' . $platform . '/' . $username;
$json = callBungie($uri);
if (isset($json['Response'][0]['membershipId']))
{
$result = array(
'membershipId' => $json['Response'][0]['membershipId'],
'membershipType' => $platform
);
}
return $result;
}
//Request characters
function fetchCharacters($username, $platform)
{
$result = array();
if($player = fetchPlayer($username, $platform)) {
$uri = 'http://bungie.net/Platform/Destiny/'.$player['membershipType'].'/Account/'.$player['membershipId'].'?ignorecase=true';
if( $json = callBungie($uri) ) {
foreach ($json['Response']['data']['characters'] as $character) {
$result[] = $character;
}
}
}
return $result;
}
//Request character descriptions
function fetchCharacterDescriptions($username, $platform)
{
$character_descriptions = array();
if($characters = fetchCharacters($username, $platform)) {
foreach ($characters as $character) {
$class = translate($character['characterBase']['classHash']);
$emblem = $character['emblemPath'];
$backgroundpath = $character['emblemPath'];
$level = $character['characterLevel'];
$character_id = $character['characterBase']['characterId'];
$light = $character['characterBase']['stats']['STAT_LIGHT']['value'];
$username = $username;
$character_descriptions[] = array(
'class'=> $class,
'emblem'=> $emblem,
'backgroundpath'=>$backgroundpath,
'character_id' => $character_id,
'characterlevel' => $level,
'light' => $light,
'username' => $username
);
}
return $character_descriptions;
}
return false;
}
?>
So my function call is: fetchCharacterDescriptions("Senaxx", "2"); and i'd like to add more players to this (from an array or something) So i can request the stats for multiple usernames.
You just have to loop over the players an perform fetchCharacterDescriptions for each of them.
$players = array(
"Senaxx" => "2",
"SomeoneElse" => "2",
);
foreach ($players as $playerName => $platformId) {
$Player = fetchCharacterDescriptions($playerName, $platformId);
// do your other stuff
}
Keep in mind that your webpage will load veeery slow because every call to fetchCharacterDescriptions() executes 2 curl requests. Also - if the API is down, your site effectivly is as well (or blank at least).
You are probably better off fetching the data beforehand (in certain intervalls) and storing it into a database/csv file or something.

Multiple PHP cUrl posts to same page

So the gist is that I need to post XML data query to a gateway page to receive a XML response which O parse later, there can be anywhere from 3-60 queries to this web service, I unfortunately have to run a simple loop right now and do them one at a time. On the response side, I will only need 1 (or a max of 5) of the lines in the response, line 2 is the first line that I need containing image data. So I'd like the ability to select which lines I am reading in if at all possible.
I created a simple "Read in" function as I said out of a basic for loop, here's the code that I am currently using and would like to revise.
$part1 = 'XML Beginning'; $part2 = XML End';
$posts = array( 0 => 'SC-010052214', 1 => 'SC-000032972', 2 => 'SC-012535460', 3 => 'SC-011257289', 4 => 'SC-010134078' );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/index.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER => 1);
curl_setopt ($ch, CURLOPT_POST, 1);
$count = count($posts);
for($i=0;$i<$count;$i++) {
curl_setopt ($ch, CURLOPT_POSTFIELDS, "payload=$part1{$posts[$i]}$part2");
$return[] = curl_exec ($ch);
}
curl_close ($ch);
print_r($return);
Restrictions: I cannot use ?post=$data0&post=$data1&post=$data3 unfortunately, so I need a better solution. Other than that, I'd like to see what kinds of improvements can be made here.
Maybe http://php.net/manual/en/function.curl-multi-init.php helps you
Because of limits in quick response,
<?php
function m_curl($input) {
// compile queries for usable locations
foreach($input['content'] as $pos=>$item) {
$query = '<childDetailQuery><request><query-replacement>';
$query .= "<item_number>{$item}</item_number>";
$query .= (isset($input['story']) && $input['story'] != NULL)
? "<story_type>".$input['story']."</story_type>"
: '<story_type>SHORT</story_type>';
$query .= (isset($input['party']) && $input['party'] != NULL)
? "<party_number>".$input['party']."</party_number>"
: '';
$query .= "</query-replacement><latency-tolerance>NONE</latency-tolerance>";
$query .= '</request></childDetailQuery>';
$queries[] = $query;
unset($query);
}
// make sure the rolling window isn't greater than the # of urls
$limit = 10;
$limit = (sizeof($queries) < $limit) ? sizeof($queries) : $limit;
$master = curl_multi_init();
$curl_arr = array();
// add additional curl options here
$std_options = array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_MAXREDIRS => 0,
);
$options = ($coptions) ? ($std_options + $coptions) : $std_options;
echo $input['location'];
// start the first batch of requests
for ($i = 0; $i < $limit; $i++) {
$ch = curl_init();
$options[CURLOPT_POSTFIELDS] = "payload=".$queries[$i];
curl_setopt_array($ch,$options);
curl_multi_add_handle($master, $ch);
}
do {
while(($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
if($execrun != CURLM_OK) {
echo 'Curl Error'; break;
}
// a request was just completed -- find out which one
while($done = curl_multi_info_read($master)) {
$info = curl_getinfo($done['handle']);
if ($info['http_code'] == 200) {
$output = curl_multi_getcontent($done['handle']);
// request successful. process output using the callback function.
parse_returns($output);
// start a new request (it's important to do this before removing the old one)
$ch = curl_init();
$options[CURLOPT_POSTFIELDS] = "payload=".$queries[$i++]; // increment i
curl_setopt_array($ch,$options);
curl_multi_add_handle($master, $ch);
// remove the curl handle that just completed
curl_multi_remove_handle($master, $done['handle']);
} else {
echo 'Failed on:'; var_dump($info);
echo 'With options:'; var_dump($options);
// request failed. add error handling.
}
}
} while ($running);
curl_multi_close($master);
return false;
}
function parse_returns($data) {
print_r($data);
}
// set query numbers
$data = array(
0 => 'SC-010052214',
1 => 'SC-000032972',
2 => 'SC-012535460',
3 => 'SC-011257289',
4 => 'SC-010134078'
);
// set options array
$options = array(
'location' => 'http://ibudev.wvus.org/websvc/actions/wvsMessageRouter.php',
'readline' => 2,
'coptions' => NULL,
'content' => $data,
'story' => 'FULL',
'party' => NULL,
);
m_curl($options);
?>

Categories