file_get_contents
Simplest HTTP client functionality using PHP standard function. Can send basic HTTP requests when combined with stream context. Lightweight with zero dependencies, suitable for prototyping and simple API calls.
Library
file_get_contents
Overview
file_get_contents is "a PHP built-in file reading function" that provides integrated HTTP request functionality as a core PHP function. Originally designed for file reading purposes, it can also function as an HTTP client by specifying URLs, supporting GET/POST requests, custom headers, authentication, SSL configuration through stream contexts. Compared to dedicated libraries like cURL, it offers simple and lightweight functionality while providing sufficient features for common web API integration, enabling easy HTTP communication in PHP applications.
Details
file_get_contents 2025 edition continues to hold an important position as the simplest HTTP communication method in the PHP 8.x era. Despite being a long-standing function since PHP 5.0, it adapts to modern HTTP communication requirements through stream context functionality. It operates with PHP standard features only without requiring external library installation, making it ideal for lightweight scripts and quick prototyping. It comprehensively supports basic HTTP features including GET/POST requests, custom headers, HTTPS support, proxy configuration, authentication, and error handling.
Key Features
- Built-in Function: Included in PHP core with no additional installation required
- Unified Interface: Consistent API for file reading and HTTP requests
- Stream Context: Detailed HTTP option configuration capabilities
- HTTPS Support: SSL/TLS communication and custom certificate configuration
- Lightweight Implementation: Fast operation with minimal overhead
- Error Handling: HTTP status code and response header access
Pros and Cons
Pros
- Available immediately without additional libraries as a PHP standard function
- Simple one-line code execution for HTTP requests
- Detailed configuration control through stream contexts
- Unified interface for file operations and HTTP communication
- Lightweight, fast, and low memory usage
- Abundant online information and learning resources
Cons
- Limited advanced features (parallel requests, detailed control) compared to cURL
- No asynchronous processing support, synchronous execution only
- Increased memory usage when downloading large files
- Basic redirect processing and cookie management
- Limited error handling with minimal debugging information
- No support for newer protocols like HTTP/2 or HTTP/3
Reference Pages
Code Examples
Basic HTTP Requests (GET/POST)
<?php
// Basic GET request
$content = file_get_contents('https://api.example.com/users');
echo $content;
// JSON response processing
$json_response = file_get_contents('https://api.example.com/data');
$data = json_decode($json_response, true);
print_r($data);
// GET request with query parameters
$params = http_build_query([
'page' => 1,
'limit' => 10,
'sort' => 'created_at'
]);
$url = 'https://api.example.com/users?' . $params;
$response = file_get_contents($url);
// POST request (form data)
$post_data = http_build_query([
'name' => 'John Doe',
'email' => '[email protected]',
'age' => 30
]);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $post_data
]
]);
$result = file_get_contents('https://api.example.com/users', false, $context);
echo $result;
// POST request (JSON sending)
$json_data = json_encode([
'name' => 'Jane Smith',
'email' => '[email protected]',
'department' => 'IT'
]);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => $json_data
]
]);
$response = file_get_contents('https://api.example.com/users', false, $context);
// PUT request (data update)
$update_data = json_encode(['name' => 'John Smith']);
$context = stream_context_create([
'http' => [
'method' => 'PUT',
'header' => 'Content-Type: application/json',
'content' => $update_data
]
]);
$response = file_get_contents('https://api.example.com/users/123', false, $context);
// DELETE request
$context = stream_context_create([
'http' => [
'method' => 'DELETE',
'header' => 'Authorization: Bearer your-token'
]
]);
$response = file_get_contents('https://api.example.com/users/123', false, $context);
?>
Stream Context and Custom Headers
<?php
// Request with custom headers
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => [
'User-Agent: MyApp/1.0 (PHP)',
'Accept: application/json',
'Accept-Language: en-US,ja-JP',
'Authorization: Bearer your-jwt-token',
'X-API-Version: v2',
'X-Request-ID: req-' . uniqid()
]
]
]);
$response = file_get_contents('https://api.example.com/data', false, $context);
// Combining multiple headers
$headers = [
'Authorization: Bearer ' . $api_token,
'Content-Type: application/json',
'Accept: application/json',
'User-Agent: MyPHPApp/1.0'
];
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => implode("\r\n", $headers)
]
]);
$data = file_get_contents('https://api.example.com/protected', false, $context);
// Basic authentication
$username = 'user';
$password = 'pass';
$auth_header = 'Authorization: Basic ' . base64_encode($username . ':' . $password);
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => $auth_header
]
]);
$content = file_get_contents('https://api.example.com/private', false, $context);
// Request with cookies
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Cookie: session_id=abc123; user_pref=dark_mode'
]
]);
$response = file_get_contents('https://api.example.com/user-data', false, $context);
// Timeout configuration
$context = stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => 30, // 30-second timeout
'header' => 'User-Agent: MyApp/1.0'
]
]);
try {
$content = file_get_contents('https://slow-api.example.com/data', false, $context);
echo "Response received successfully\n";
} catch (Exception $e) {
echo "Timeout or error: " . $e->getMessage() . "\n";
}
// Proxy configuration
$context = stream_context_create([
'http' => [
'method' => 'GET',
'proxy' => 'tcp://proxy.example.com:8080',
'request_fulluri' => true,
'header' => 'Proxy-Authorization: Basic ' . base64_encode('proxy_user:proxy_pass')
]
]);
$response = file_get_contents('https://api.example.com/data', false, $context);
?>
HTTPS Configuration and SSL Control
<?php
// Basic HTTPS connection
$content = file_get_contents('https://secure-api.example.com/data');
// Disable SSL certificate verification (development environment only)
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false
]
]);
$response = file_get_contents('https://self-signed.example.com/api', false, $context);
// Detailed SSL certificate configuration
$context = stream_context_create([
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'cafile' => '/path/to/ca-bundle.crt',
'local_cert' => '/path/to/client.pem',
'local_pk' => '/path/to/client.key',
'passphrase' => 'client-key-password'
],
'http' => [
'method' => 'GET',
'header' => 'User-Agent: SecureApp/1.0'
]
]);
$secure_data = file_get_contents('https://enterprise-api.example.com/data', false, $context);
// Encryption configuration
$context = stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
'verify_peer' => true,
'verify_peer_name' => true,
'ciphers' => 'HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK'
]
]);
$response = file_get_contents('https://high-security-api.example.com/data', false, $context);
// SNI (Server Name Indication) support
$context = stream_context_create([
'ssl' => [
'SNI_enabled' => true,
'SNI_server_name' => 'api.example.com'
]
]);
$content = file_get_contents('https://api.example.com/data', false, $context);
?>
Error Handling and Response Information Retrieval
<?php
// Ignore errors and retrieve response
$context = stream_context_create([
'http' => [
'method' => 'GET',
'ignore_errors' => true, // Also retrieve error responses
'header' => 'User-Agent: MyApp/1.0'
]
]);
$response = file_get_contents('https://api.example.com/might-fail', false, $context);
// Check response headers
if ($response !== false) {
// Response headers are stored in global variable $http_response_header
echo "Response Headers:\n";
foreach ($http_response_header as $header) {
echo $header . "\n";
}
// Extract status code
if (isset($http_response_header[0])) {
preg_match('/HTTP\/\d\.\d\s+(\d+)/', $http_response_header[0], $matches);
$status_code = isset($matches[1]) ? (int)$matches[1] : 0;
echo "Status Code: " . $status_code . "\n";
if ($status_code >= 200 && $status_code < 300) {
echo "Success response\n";
$data = json_decode($response, true);
} elseif ($status_code >= 400) {
echo "Error response: " . $response . "\n";
}
}
}
// Comprehensive error handling function
function safe_http_request($url, $options = []) {
$default_options = [
'http' => [
'method' => 'GET',
'timeout' => 30,
'ignore_errors' => true,
'header' => 'User-Agent: SafeHTTPClient/1.0'
]
];
// Merge options
$context_options = array_merge_recursive($default_options, $options);
$context = stream_context_create($context_options);
// Execute request
$response = @file_get_contents($url, false, $context);
if ($response === false) {
$error = error_get_last();
throw new Exception("HTTP request failed: " . ($error['message'] ?? 'Unknown error'));
}
// Parse response information
global $http_response_header;
$status_code = 0;
$response_headers = [];
if (isset($http_response_header)) {
foreach ($http_response_header as $header) {
if (preg_match('/HTTP\/\d\.\d\s+(\d+)/', $header, $matches)) {
$status_code = (int)$matches[1];
}
$response_headers[] = $header;
}
}
return [
'status_code' => $status_code,
'headers' => $response_headers,
'body' => $response,
'success' => $status_code >= 200 && $status_code < 300
];
}
// Usage example
try {
$result = safe_http_request('https://api.example.com/data', [
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode(['key' => 'value'])
]
]);
if ($result['success']) {
echo "Success: " . $result['body'] . "\n";
} else {
echo "Error (Status: {$result['status_code']}): " . $result['body'] . "\n";
}
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . "\n";
}
// File saving and HTTP download
function download_file($url, $local_path, $headers = []) {
$context_options = [
'http' => [
'method' => 'GET',
'timeout' => 300, // 5-minute timeout
'header' => array_merge([
'User-Agent: FileDownloader/1.0'
], $headers)
]
];
$context = stream_context_create($context_options);
$content = file_get_contents($url, false, $context);
if ($content === false) {
throw new Exception("Failed to download file");
}
$bytes_written = file_put_contents($local_path, $content);
if ($bytes_written === false) {
throw new Exception("Failed to save file");
}
return $bytes_written;
}
// Usage example
try {
$bytes = download_file(
'https://example.com/large-file.zip',
'/tmp/downloaded.zip',
['Authorization: Bearer your-token']
);
echo "Download completed: {$bytes} bytes\n";
} catch (Exception $e) {
echo "Download error: " . $e->getMessage() . "\n";
}
?>
Practical API Client Implementation
<?php
// Reusable API client class
class SimpleAPIClient {
private $base_url;
private $default_headers;
private $timeout;
public function __construct($base_url, $headers = [], $timeout = 30) {
$this->base_url = rtrim($base_url, '/');
$this->default_headers = $headers;
$this->timeout = $timeout;
}
public function get($endpoint, $params = [], $headers = []) {
$url = $this->base_url . '/' . ltrim($endpoint, '/');
if (!empty($params)) {
$url .= '?' . http_build_query($params);
}
return $this->request('GET', $url, null, $headers);
}
public function post($endpoint, $data = null, $headers = []) {
$url = $this->base_url . '/' . ltrim($endpoint, '/');
return $this->request('POST', $url, $data, $headers);
}
public function put($endpoint, $data = null, $headers = []) {
$url = $this->base_url . '/' . ltrim($endpoint, '/');
return $this->request('PUT', $url, $data, $headers);
}
public function delete($endpoint, $headers = []) {
$url = $this->base_url . '/' . ltrim($endpoint, '/');
return $this->request('DELETE', $url, null, $headers);
}
private function request($method, $url, $data = null, $headers = []) {
$all_headers = array_merge($this->default_headers, $headers);
$context_options = [
'http' => [
'method' => $method,
'timeout' => $this->timeout,
'ignore_errors' => true,
'header' => implode("\r\n", $all_headers)
]
];
if ($data !== null) {
if (is_array($data) || is_object($data)) {
$context_options['http']['content'] = json_encode($data);
$context_options['http']['header'] .= "\r\nContent-Type: application/json";
} else {
$context_options['http']['content'] = $data;
}
}
$context = stream_context_create($context_options);
$response = @file_get_contents($url, false, $context);
if ($response === false) {
throw new Exception("HTTP request failed for: $url");
}
global $http_response_header;
$status_code = 0;
if (isset($http_response_header[0])) {
preg_match('/HTTP\/\d\.\d\s+(\d+)/', $http_response_header[0], $matches);
$status_code = isset($matches[1]) ? (int)$matches[1] : 0;
}
return [
'status_code' => $status_code,
'headers' => $http_response_header ?? [],
'body' => $response,
'data' => json_decode($response, true)
];
}
}
// API client usage example
$client = new SimpleAPIClient('https://api.example.com/v1', [
'Authorization: Bearer your-api-token',
'User-Agent: MyApp/1.0'
]);
try {
// Get user list
$users = $client->get('users', ['page' => 1, 'limit' => 10]);
if ($users['status_code'] == 200) {
echo "User count: " . count($users['data']) . "\n";
}
// Create new user
$new_user = $client->post('users', [
'name' => 'Alice Johnson',
'email' => '[email protected]',
'role' => 'user'
]);
if ($new_user['status_code'] == 201) {
echo "User creation success: ID=" . $new_user['data']['id'] . "\n";
// Update user information
$updated = $client->put("users/{$new_user['data']['id']}", [
'name' => 'Alice Smith'
]);
if ($updated['status_code'] == 200) {
echo "User update success\n";
}
}
} catch (Exception $e) {
echo "API error: " . $e->getMessage() . "\n";
}
// Webhook handling
function handle_webhook($payload, $signature, $secret) {
// Signature verification
$expected_signature = 'sha256=' . hash_hmac('sha256', $payload, $secret);
if (!hash_equals($expected_signature, $signature)) {
throw new Exception('Invalid webhook signature');
}
$data = json_decode($payload, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Invalid JSON payload');
}
// Notify external API
$notification_context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nAuthorization: Bearer internal-token",
'content' => json_encode([
'event' => $data['event'] ?? 'unknown',
'timestamp' => date('c'),
'data' => $data
]),
'timeout' => 10
]
]);
$result = file_get_contents('https://internal-api.example.com/webhooks', false, $notification_context);
return $result !== false;
}
// Form data submission example
function submit_form($url, $form_data, $files = []) {
$boundary = 'boundary' . uniqid();
$content = '';
// Form fields
foreach ($form_data as $name => $value) {
$content .= "--{$boundary}\r\n";
$content .= "Content-Disposition: form-data; name=\"{$name}\"\r\n\r\n";
$content .= "{$value}\r\n";
}
// Files
foreach ($files as $field_name => $file_path) {
if (file_exists($file_path)) {
$filename = basename($file_path);
$file_content = file_get_contents($file_path);
$mime_type = mime_content_type($file_path) ?: 'application/octet-stream';
$content .= "--{$boundary}\r\n";
$content .= "Content-Disposition: form-data; name=\"{$field_name}\"; filename=\"{$filename}\"\r\n";
$content .= "Content-Type: {$mime_type}\r\n\r\n";
$content .= "{$file_content}\r\n";
}
}
$content .= "--{$boundary}--\r\n";
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: multipart/form-data; boundary={$boundary}",
'content' => $content
]
]);
return file_get_contents($url, false, $context);
}
// Usage example
$response = submit_form('https://upload.example.com/submit', [
'title' => 'Document',
'category' => 'report'
], [
'document' => '/path/to/document.pdf'
]);
echo "Form submission completed\n";
?>