Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
CURL context options in PHP
In PHP, CURL context options allow you to configure HTTP and FTP requests when using stream contexts with functions like file_get_contents() or fopen(). These options provide fine-grained control over request behavior without directly using the cURL extension.
Note: CURL context options are available when the CURL extension was compiled using the --with-curlwrappers configure option (deprecated in newer PHP versions).
Available CURL Context Options
| Option | Description |
|---|---|
| method | HTTP method supported by the remote server. Defaults to GET. |
| header | Additional headers to be sent during request |
| user_agent | Value to send with User-Agent: header. |
| content | Additional data to be sent after the headers. Not used for GET or HEAD requests. |
| proxy | URI specifying address of proxy server. |
| max_redirects | The max number of redirects to follow. Defaults to 20. |
| curl_verify_ssl_host | Verify the host. Defaults to FALSE. Available for both HTTP and FTP. |
| curl_verify_ssl_peer | Require verification of SSL certificate used. Defaults to FALSE. |
Example Usage
Here's how to create a stream context with CURL options for making HTTP requests −
<?php
// Create context with CURL options
$context = stream_context_create([
'curl' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r<br>" .
"Authorization: Bearer token123\r<br>",
'user_agent' => 'MyApp/1.0',
'content' => json_encode(['name' => 'John', 'age' => 30]),
'max_redirects' => 5,
'curl_verify_ssl_peer' => true
]
]);
// Make request using the context
$response = file_get_contents('https://api.example.com/users', false, $context);
echo $response;
?>
SSL Configuration Example
For secure connections, you can configure SSL verification options −
<?php
$context = stream_context_create([
'curl' => [
'method' => 'GET',
'curl_verify_ssl_host' => true,
'curl_verify_ssl_peer' => true,
'user_agent' => 'SecureClient/2.0'
]
]);
$data = file_get_contents('https://secure-api.example.com/data', false, $context);
?>
Conclusion
CURL context options provide a convenient way to configure HTTP requests through stream contexts in PHP. While deprecated in newer versions, they offer useful request customization capabilities for legacy applications.
Advertisements
