Using PHP stream_context_create to Configure HTTP Options and Send Requests

This article explains PHP's stream_context_create function, detailing its purpose, parameters, and return value, and provides two complete examples showing how to configure HTTP options, send GET and POST requests, and process the response using fopen or file_get_contents.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP stream_context_create to Configure HTTP Options and Send Requests

The stream_context_create function creates and returns a stream context resource that contains the options and parameters you specify, allowing you to customize HTTP requests.

Signature:

resource stream_context_create([array $options [, array $params]])

Parameters:

options : a two‑dimensional associative array in the form $arr['wrapper']['option'] = $value. Default is an empty array.

params : an associative array in the form $arr['parameter'] = $value.

Return value: a stream context resource of type resource.

Example 1 (GET request with custom headers):

<?php
$opts = array(
    'http' => array(
        'method'  => "GET",
        'header'  => "Accept-language: en
".
                    "Cookie: foo=bar
"
    )
);
$context = stream_context_create($opts);
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>

Example 2 (POST request with form data):

<?php
$data = array(
    'name'   => 'zhangsan',
    'gender' => 'male',
    'age'    => 25
);
$query_string = http_build_query($data);
$option = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => "Content-type:application/x-www-form-urlencoded
".
                    "Content-length:" . strlen($query_string) . "
",
        'content' => $query_string
    )
);
$context = stream_context_create($option);
$url = 'http://localhost/test.php';
$content = file_get_contents($url, false, $context);
echo $content;
?>

Sample output from Example 2:

Array ( [name] => zhangsan [gender] => male [age] => 25 )
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

examplerequeststream_context_create
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.