Home > Back-end >  2 JSON Curl Requests in a PHP file in sequence?
2 JSON Curl Requests in a PHP file in sequence?

Time:08-25

I have PHP code to execute 2 Curl calls to the same URL with different data. It works but there is some lag (a few seconds) between the first and the 2nd. i have looked at curl multi but cannot figure out how to use it for JSON arrays. please help?

<?php
$data = array("epic" => $epic, "expiry" => "DFB");
$data_string = json_encode($data);

$headers = array(
'Content-Type: application/json; charset=UTF-8',
'Accept: application/json; charset=UTF-8',
'X-IG-API-KEY: '.$xapikey,
'Version: 1',
'X-SECURITY-TOKEN: '.$_SESSION['api_xtoken'],
'CST: ' .$_SESSION['api_cst'],
'_method: DELETE',

);
$ch = curl_init('' . $trading_url . '');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

    
$data2 = array("currencyCode" => "GBP", "direction" => $tv_direction);
$data_string2 = json_encode($data2);


$ch2 = curl_init('' . $trading_url . '');
curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch2, CURLOPT_VERBOSE, 1);
curl_setopt($ch2, CURLOPT_HEADER, 1);
curl_setopt($ch2, CURLOPT_POSTFIELDS,$data_string2);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers2);

$result2 = curl_exec($ch2); 






CodePudding user response:

You are opening curl connection two times also you have not closed the connection once the request has been completed you need to close the connection

can try something like this

$data_string = json_encode($data);

$headers = array(
'Content-Type: application/json; charset=UTF-8',
'Accept: application/json; charset=UTF-8',
'X-IG-API-KEY: '.$xapikey,
'Version: 1',
'X-SECURITY-TOKEN: '.$_SESSION['api_xtoken'],
'CST: ' .$_SESSION['api_cst'],
'_method: DELETE',

);
$ch = curl_init('' . $trading_url . '');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

    
$data2 = array("currencyCode" => "GBP", "direction" => $tv_direction);
$data_string2 = json_encode($data2);


curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);

$result2 = curl_exec($ch); 
    curl_close($ch);

CodePudding user response:

You can start them simultaneously using stream_socket_client()

You can also use stream_socket_client() to make calls to two of your own php scripts where each of your curl requests are in each script.
You then call your two scripts using stream_socket_client() where the urls used are to your own scripts.

It's not simple to use sockets, so I included some code I wrote 10 years ago. As I remember it took a day or two to get it working

What this script does is validate webpages using the W3C CSS and HTML validator tools and webpage speed test to evaluate how well a webpage was designed. Calling them in parallel reduced the time significantly vs making the requests serially.
You may want to use a newer user agent.

  ini_set('user_agent', 'Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0');
  set_time_limit (60);
  $timeout = 120; 
  $result = array(); 
  $sockets = array(); 
  $buffer_size = 8192;
  $id = 0;
  $urls = array();
  $path = $url;
  $url = urlencode("$url");
  $urls[] = array('host' => "jigsaw.w3.org",'path' => "/css-validator/validator?uri=$url&profile=css3&usermedium=all&warning=no&lang=en&output=text");
  $urls[] = array('host' => "validator.w3.org",'path' => "/check?uri=$url&charset=(detect automatically)&doctype=Inline&group=0&output=json");
  $urls[] = array('host' => "validator.w3.org",'path' => "/check?uri=$url&charset=(detect automatically)&doctype=XHTML Basic 1.1&group=0&output=json");
  $urls[] = array('host' => "www.webpagetest.org",'path' => "/runtest.php?f=xml&bwDown=10000&bwUp=1500&latency=40&fvonly=1&k=1a736137bdd4ea914a6fc7ca06f71a&url=$url");
  $err = '';
  foreach($urls as $path){
    $host = $path['host'];
    $path = $path['path'];
    $http = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";
  //  echo "<br/>\n=>$host<br/>\n=>$path<br/>\n=>$http<br/>\n";
    $stream = stream_socket_client("$host:80", $errno,$errstr, 120,STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT); 
    if ($stream) {
      $sockets[] = $stream;  // supports multiple sockets
      $start[] = microtime(true);
      fwrite($stream, $http);
    }
    else { 
   $err .=  "$id Failed<br>\n";
    }
  }

while (count($sockets)) {
  $read = $sockets; 
  stream_select($read, $write = NULL, $except = NULL, $timeout);
  if (count($read)) {
    foreach ($read as $r) { 
      $id = array_search($r, $sockets); 
      $data = fread($r, $buffer_size); 
      if (strlen($data) == 0) { 
     //   echo "$id Closed: " . date('h:i:s') . "\n\n\n";
        $closed[$id] = microtime(true);
        fclose($r); 
        unset($sockets[$id]);
      } 
      else {
        $result[$id] .= $data; 
      }
    }
  }
  else { 
 //   echo 'Timeout: ' . date('h:i:s') . "\n\n\n";
    break;
  }
}
  • Related