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.
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:
Example of using file_get_contents() function to send a GET request in PHP
<?php
$url = 'https://jsonplaceholder.typicode.com/posts';
$data = file_get_contents($url);
if ($data === false) {
echo "Request failed.";
} else {
echo $data;
}Note:
file_get_contents()requires theallow_url_fopendirective to be enabled inphp.ini. It is disabled by default on many servers.
Here's an example using cURL:
How to send a GET request from PHP using cURL?
<?php
$url = 'https://jsonplaceholder.typicode.com/posts';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch);
} else {
echo $data;
}
curl_close($ch);
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
You can also use PHP stream contexts, which provide a built-in way to configure HTTP requests. Here's an example using stream contexts:
Example of using PHP stream contexts to send a GET request
<?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);
if ($data === false) {
echo "Request failed.";
} else {
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:
How to send a GET request with a query string in PHP?
<?php
$url = 'http://example.com';
$query = http_build_query(array('key' => 'value'));
$data = file_get_contents($url . '?' . $query);
if ($data === false) {
echo "Request failed.";
} else {
echo $data;
}