How to send a GET request from PHP?
To send a GET request from PHP, you can use the file_get_contents function or the cURL extension. Here's an example using file_get_contents:
<?php
$url = 'https://jsonplaceholder.typicode.com/posts';
$data = file_get_contents($url);
echo $data;
Here's an example using cURL:
<?php
$url = 'https://jsonplaceholder.typicode.com/posts';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
echo $data;
curl_close($ch);
Watch a video course
Learn object oriented PHP
You can also use the HTTP extension (http
), which provides a more powerful interface for making HTTP requests. Here's an example using the HTTP extension:
<?php
$url = 'https://jsonplaceholder.typicode.com/posts';
$options = [
'http' => [
'method' => 'GET',
'header' => 'Content-type: application/x-www-form-urlencoded',
],
];
$context = stream_context_create($options);
$data = file_get_contents($url, false, $context);
echo $data;
If you want to send a GET request with a query string (e.g., http://example.com?key=value
), you can use the http_build_query
function to build the query string, and then append it to the URL using the ?
character. Here's an example:
<?php
$url = 'http://example.com';
$query = http_build_query(array('key' => 'value'));
$data = file_get_contents($url . '?' . $query);