cURL – How to send and fetch data in WordPress

BACKGROUND

After the user on domain1 clicks a link to domain 2, I need to send also the user-data (username,email,..) from server1/domain1 to server2/domain2 and to save it temporary in the server2/database.

Both are wordpress websites.

CURRENT WORK

Lets say, $url="http://my-domain2.com";
So far I found out, that cURL can do this job:

function curlTest($url, $fields){

  try{

      $ch = curl_init($url);

      if (!$ch)
        throw new Exception('Failed to initialize');

      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 10);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
      curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
      $response = curl_exec($ch);

      $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      if (!$response)
        throw new Exception(curl_error($ch), curl_errno($ch));


      curl_close( $ch );
      return (int) $status; //status 200 = success


      } catch(Exception $e) {

          trigger_error(sprintf(
              'Curl failed with error #%d: %s',
              $e->getCode(), $e->getMessage()),
              E_USER_ERROR);

      }
}

or objective orientated like descriped here.

Later I found a wordpress solution like this:

 $response = wp_remote_post( &url, array( 'data' => $fields) );

explained here.

The cURL call seems to be successfully, but I have no idea how to fetch the data on the other server.
So far I put the user-data on server1 in an array ($fields) and using POST to send it to server2. But how can I fetch the data on server2?

According to the example of Ed Cradock below the offical documentation it seems to be possible to grap the request on the other side with this code:

   if($_SERVER['REQUEST_METHOD'] == 'PUT') 
    { 
       parse_str(file_get_contents('php://input'), $requestData); 

       print_r($requestData); 

       // Save requested Data to database here
    } 

But it doesn’t work for me because I guess the URL is wrong: http://my-domain2.com/<whats-here?>

QUESTION

How to fetch the Data of a POST cURL request with wordpress in a secure way?

2 Answers
2

wp_remote_get()
and wp_remote_post() and wp_remote_request() should answer on your questions.This is best practice for WordPress.

Leave a Comment