Search code examples
phpparameter-passingsubdomain

What is the best way to send parameters to a subdomain in PHP


I have a situation and I do not know how to solve it. I have a domain named domain.com and a subdomain named sub.domain.com

Now, I have some processing in PHP to do on domain.com and I want to pass some variables and receive a response from the sub.domain.com. This can be achieved through arrays encoded in JSON. So,

  1. domain.com/process.php creates a PHP array of parameters (encoded in JSON).
  2. domain.com/process.php calls the sub.domain.com/index.php?key=validationKey&params=.... to perform a calculation
  3. sub.domain.com/index.php?key=validation_key&params=.... does its calculation and then returns an array encoded in JSON to domain.com/process.php
  4. domain.com/process.php does something with that data.

How can I achieve this?

Thanks in advance for any solution


Solution

  • The obvious solution here would be to execute the PHP code directly, but assuming that's not possible for some reason(sub.domain.com is on a different server, perhaps) then you can send data back and forth using cURL

    Given that significant amounts of data to a query string can sometimes be problematic, this code uses POST.

    In domain.com your code would look something like this:

    <?php
    
    $key = "validKey";
    $data = json_encode(['data'=>[1,2,3], 'moreData'=>[4,5,6]]);
    $payload = ['key'=>$key, 'params'=>$data];
    
    echo "Setting up cURL<br>";
    
    // I've used sub.domain.com here, but the URL could be anything
    $ch = curl_init('http://sub.domain.com/processor.php');
    
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    
    echo "Executing cURL<br>";
    $result = curl_exec($ch);
    $responseCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE );
    if ($responseCode != "200") {
        exit("Error: Response $responseCode");
    }
    echo "Received response<br>";
    
    $response = json_decode($result);
    var_dump($response);
    

    The code in sub.domain.com (I've called it 'processor.php' above) would then be:

    <?php
    
    // Simple key validation function
    function isValidKey(string $key):bool {
        // Do whatever validation you need here
        return ($key === "validKey");
    }
    
    // Simple entry validation. Return a 404 to discourage anyone just poking about
    if (($_SERVER['REQUEST_METHOD'] !== 'POST') ||
        (empty($_POST['key']))
        ) {
        http_response_code(404);
        exit;
        }
    
        // Invalid key? return 401 Unauthorised
        if (!isValidKey($_POST['key'])) {
            http_response_code(401);
            exit;
        }
    
        // No params, or not JSON, return 400 Bad Request
        if (empty($_POST['params']) || (is_null($data=json_decode($_POST['params'])))) {
            http_response_code(400);
            exit;
        }
    
        // process data here. Return results
    
        header("Content-type: application/json");
        $result = ['status'=>'OK','answer'=>'Answer', "data"=>$data ];
    
        echo json_encode($result);
    

    If everything works, running the domain.com code from a browser should give this result:

    Setting up cURL
    Executing cURL
    Received response
    
    /home/domain.com/html/process.php:28:
    object(stdClass)[1]
      public 'status' => string 'OK' (length=2)
      public 'answer' => string 'Answer' (length=6)
      public 'data' => 
        object(stdClass)[2]
          public 'data' => 
            array (size=3)
              0 => int 1
              1 => int 2
              2 => int 3
          public 'moreData' => 
            array (size=3)
              0 => int 4
              1 => int 5
              2 => int 6
    

    Disclaimer: This is proof-of-concept code only. It's not production-ready, and has had only rudimentary testing.