Intermediate LevelPHP 8+
How do you make HTTP POST requests with custom headers using file_get_contents() and stream_context_create()?
❓ Interview Prompt: Explain stream_context_create(), http stream options array, custom HTTP headers, POST bodies, and file_get_contents().
While 'file_get_contents("https://...")' performs simple HTTP GET requests by default, passing a custom stream context created via 'stream_context_create()' enables sending HTTP POST requests, custom headers, and timeouts without cURL!
Code Implementation Example
php
<?php
$url = 'https://api.example.com/orders';
$data = json_encode(['sku' => 'BOOK-1', 'qty' => 2]);
// Configure HTTP stream options
$options = [
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json
" .
"Authorization: Bearer token_xyz
",
'content' => $data,
'timeout' => 5.0
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);💡Executing HTTP POST requests with headers using file_get_contents and stream_context_create.
🎯 Interview Key Takeaway
Pass stream_context_create() options to file_get_contents() to execute HTTP POST requests with custom headers and timeouts.
#stream_context_create#file_get_contents#HTTP POST#Intermediate
Back to all PHP 8+ Questions→