Alternative of cURL in PHP
If you want to make an HTTPS request without using cURL in PHP, you can use alternative methods like file_get_contents(), stream_context_create(), or Guzzle. Here are different ways to do it:
1️⃣ Using file_get_contents()
with Stream Context
This is the simplest alternative to cURL.
<?php
$url = ""; // Replace with your actual API URL$options = [
"http" => [
"method" => "GET", // Change to "POST" if needed
"header" => "User-Agent: PHP\r\n" .
"Accept: application/json\r\n"
],
"ssl" => [
"verify_peer" => true,
"verify_peer_name" => true,
]
];$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);if ($response === false) {
die("Error fetching data");
}echo $response;
?>
✅ Pros: Simple, built-in
❌ Cons: Limited error handling, no advanced request configurations
2️⃣ Using stream_context_create()
for a POST
Request
If you need to send data via POST, modify the method
and include a content
field.
<?php
$url = ""; // Replace with your API
$data = http_build_query([
"param1" => "value1",
"param2" => "value2"
]);
$options = [
"http" => [
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n" .
"User-Agent: PHP\r\n",
"content" => $data
],
"ssl" => [
"verify_peer" => true,
"verify_peer_name" => true,
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($response === false) {
die("Error in request");
}
echo $response;
?>
✅ Pros: Supports GET & POST, more control than file_get_contents()
❌ Cons: Still lacks detailed error handling
3️⃣ Using Guzzle (Recommended for Complex Requests)
Guzzle is a powerful PHP HTTP client that handles requests efficiently.
Install Guzzle via Compose
composer require guzzlehttp/guzzle
PHP Code Using Guzzle
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', 'https://pardarsy.railnet.gov.in/api-endpoint', [
'headers' => [
'User-Agent' => 'PHP-Guzzle',
'Accept' => 'application/json'
]
]);
echo $response->getBody();
?>
✅ Pros: Best for advanced requests (headers, authentication, JSON support)
❌ Cons: Requires Composer & Guzzle package installation
Which One Should You Use?
MethodBest ForProsConsfile_get_contents()
Simple requestsEasy to useLimited error handlingstream_context_create()
Simple GET/POSTNo extra setupHarder debuggingGuzzle (Recommended)Advanced requests (APIs, JSON, Auth)Powerful, error handlingRequires Composer
Let me know if you need further help! 🚀