Search code examples
phpget

Making a GET request to another PHP file in PHP


I have created a php file called "brain.php" that takes a get parameter of "message" - so for example "brain.php?msg=hello". It will respond with a JSON array that can be handled by the application.

I have built a JQuery app that can make these requests, and now I'm attempting to do it in PHP but I'm not sure how.

The following code does not work as it thinks the parameter is part of the filename

$response = file_get_contents("../brain.php?msg=hello");
echo $response;

The following code kind of works but simply responds with the entirety of the code instead of the response

$response = file_get_contents("../brain.php");
echo $response;

What is the best way to make the request with the ?msg variable and store the JSON response in a variable for handling?

Thank you!


Solution

  • You can get content from URL using file_get_contents:

    $response  = file_get_contents('https://httpbin.org/ip?test=test');
    $jsonData = json_decode($response, true));
    

    However you need to check if allow_url_fopen is enabled in your php.ini. Alternatively you can do the same with curl:

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'https://httpbin.org/ip?test=test');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    
    $jsonData = json_decode(curl_exec($curl), true);
    
    curl_close($curl);