Function: Create and return a text data stream and apply various options, which can be used for fopen (), file_get_contents (), and other procedures such as timeout settings, proxy server, request mode, header information set special procedures.
Function Prototypes: Resource stream_context_create ([array $options [, array $params]])
Usage
Example One:
Copy Code code as follows:
<?php
$opts = Array (' Http-->array (
' Method ' => ' get ',
' Header ' => ' accept-language:en\r\n '.
"Cookie:foo=bar\r\n"
)
);
$context = Stream_context_create ($opts);
/* Sends an HTTP request to Www.jb51.net
With additional headers shown above * *
$fp = fopen (' http://www.jb51.net ', ' R ', false, $context);
Fpassthru ($FP);
Fclose ($FP);
?>
Example Two:
Copy Code code as follows:
<?php
$opts = Array (' Http-->array (
' Method ' => ' get ',
' Header ' => ' accept-language:en\r\n '.
"Cookie:foo=bar\r\n"
)
);
$context = Stream_context_create ($opts);
?>
You are would setup the header this way:
<?php
$opts = Array (' Http-->array (
' Method ' => ' get ',
' Header ' =>array ("Accept-language:en",
"Cookie:foo=bar",
"Custom-header:value")
)
);
$context = Stream_context_create ($opts);
?>
Example Three:
Copy Code code as follows:
<?php
$opts = Array (' http ' => array (' proxy ' => ' tcp://127.0.0.1:8080 ', ' Request_fulluri ' => true));
$context = Stream_context_create ($opts);
$data = file_get_contents (' Http://www.jb51.net ', false, $context);
Echo $data;
?>
Example four:
Copy Code code as follows:
<?php
function Do_post_request ($url, $postdata, $files = null)
{
$data = "";
$boundary = "---------------------". SUBSTR (MD5 (rand (0,32000)), 0, 10);
Collect PostData
foreach ($postdata as $key => $val)
{
$data. = "-$boundary \ n";
$data. = "Content-disposition:form-data; Name=\ "". $key. " \ n \ nthe. $val. " \ n ";
}
$data. = "-$boundary \ n";
Collect Filedata
foreach ($files as $key => $file)
{
$fileContents = file_get_contents ($file [' tmp_name ']);
$data. = "Content-disposition:form-data; Name=\ "{$key}\"; Filename=\ ' {$file [' name ']}\ ' \ n ';
$data. = "content-type:image/jpeg\n";
$data. = "content-transfer-encoding:binary\n\n";
$data. = $fileContents. " \ n ";
$data. = "--$boundary--\n";
}
$params = Array (' http ' => array (
' Method ' => ' POST ',
' Header ' => ' Content-type:multipart/form-data; Boundary= '. $boundary,
' Content ' => $data
));
$ctx = Stream_context_create ($params);
$fp = fopen ($url, ' RB ', false, $ctx);
if (! $fp) {
throw new Exception ("Problem with $url, $php _errormsg");
}
$response = @stream_get_contents ($FP);
if ($response = = False) {
throw new Exception ("Problem reading data from $url, $php _errormsg");
}
return $response;
}
Set data (in the example from post)
Sample Data
$postdata = Array (
' Name ' => $_post[' name ',
' Age ' => $_post[' age '],
' Sex ' => $_post[' sex ']
);
Sample image
$files [' image '] = $_files[' image '];
Do_post_request ("Http://www.jb51.net", $postdata, $files);
?>