How to make a get request PHP

Make a GET request in PHP with a step-by-step example: create a URL, use the file_get_contents() function, and more.

Making a GET Request in PHP

Making a GET request using PHP is a relatively straightforward process. In this example we will use the file_get_contents() function, which is a simple way to make a GET request.

$url = 'http://example.com/api/endpoint'; 
$data = file_get_contents($url);
The file_get_contents() function will return a string containing the response body. If the request was successful, you can then use the response data in your application. If the request was not successful, you can use the $http_response_header variable to determine the response code, which can be used to determine what went wrong.

if ($data === FALSE) {
    list($version, $status_code, $msg) = explode(' ', $http_response_header[0], 3);
    if ($status_code !== 200) {
        echo "Request failed: $status_code $msgn";
    }
}
If you need to send data along with the request, you can use the stream_context_create() and file_get_contents() functions. This example uses the POST method to send data to the API endpoint.

$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

$options = array(
    'http' => array(
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
You can also use the curl_init() function to make a GET request. This example uses the GET method to send data to the API endpoint.

$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

$url = $url . '?' . http_build_query($data);
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
Using either of these methods, you can make GET requests in PHP. The file_get_contents() function is a simple way to make a request, while the curl_init() function provides more flexibility.

Answers (0)