KDJ KDJ - 2 months ago 11
PHP Question

using php curl to pass variables to another site

I saw the following code on another post...

<?php
$ch = curl_init(); // create curl handle

$url = "http://www.google.com";
/**
* For https, there are more options that you must define, these you can get from php.net
*/
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query(['array_of_your_post_data']));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3); //timeout in seconds
curl_setopt($ch,CURLOPT_TIMEOUT, 20); // same for here. Timeout in seconds.
$response = curl_exec($ch);

curl_close ($ch); //close curl handle

echo $response;
?>


The only thing is I have no clue how to actually implement it or how it will work.

Here is what I am trying to do...

sitea.com/setup is setting php variables. If you visited that page, it would set $var1 = "hello" $var2="hi"

If someone visits siteb.com, I want to use php and somehow get those variables from sitea.com/setup to siteb.com and set them as new php variables. I'm assuming curl is the best option from what I've read, but can't figure out how to get it to work (or where to put it and how to call it) for that matter.

I'm experimenting with code trying to see how to do something for an upcoming project. Any help would be greatly appreciated.

I should note that I need this to be able to work from one domain on server1 to another domain on server2.

Answer

In a simple way it can be done like:

Site a: file.php

<?php
$a = 10;
$b = 20;
echo $a . ':' . $b;
?>

Site b: curl.php

<?php
  $ch = curl_init(); // create curl handle

  $url = "http://sitea/file.php";
  /**
   * For https, there are more options that you must define, these you can get from php.net 
   */
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST, true);
  curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query(['array_of_your_post_data']));
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3); //timeout in seconds
  curl_setopt($ch,CURLOPT_TIMEOUT, 20); // same for here. Timeout in seconds.
  $response = curl_exec($ch);

  curl_close ($ch); //close curl handle

  echo $response;
  $parts = explode(':', $response);
  $var1 = $parts[0];
  $var2 = $parts[1];
?>