ホームページ  >  記事  >  バックエンド開発  >  PHP stream_context_create() 関数と使用法の分析_PHP チュートリアル

PHP stream_context_create() 関数と使用法の分析_PHP チュートリアル

WBOY
WBOYオリジナル
2016-07-21 15:31:28741ブラウズ

機能: テキストデータストリームの作成と返却、fopen()やfile_get_contents()などの処理のタイムアウト設定、プロキシサーバー、リクエストメソッド、ヘッダ情報の設定などの特殊な処理に使用できます。
関数プロトタイプ: resource stream_context_create ([ array $options [, array $params ]] )
使用方法
例 1:

コードをコピー コードは次のとおりです:

$ opts = array ( 'http-->array(
'method'=>"GET",
'header'=>"Accept- language: enrn" .
"Cookie: foo=barrn"
)
) ;
$ context = stream_context_create($opts);
/* 上記の追加ヘッダーを使用して http リクエストを www.jb51.net に送信します */
$fp = fopen('http://www.jb51.net', 'r' 、 false、 $context);
fclose($fp);
?> php
$opts = array( 'http-->array(
'method'=>) GET",
'header'=>"Accept- language: enrn" .
"Cookie: foo=barrn"
) ); $context = stream_context_create($opts);
?>
ヘッダーは次のようになります: $opts = array( 'http-->array( 'method' =>"GET", 'header'=>array("Accept- language: en" ,
"Cookie: foo=bar",
"Custom-Header: value")
)
);
$context = stream_context_create($opts)?> ('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;
?> do_post_request($url, $postdata, $files = null)
{
$data = ""; ------".substr(md5(rand(0,32000)), 0, 10);
//Postdata を収集
foreach($postdata as $key => $val)
{
$data . = "--$boundaryn";
$data .= "Content-Disposition: form-data; name="".$key.""nn".$val."n";
}
$data .= " --$boundaryn";
/ /Collect Filedata
foreach($files as $key => $file)
{
$fileContents = file_get_contents($file['tmp_name']);
$data .= "コンテンツ-性質: form-data; name= "{$key}"; filename="{$file['name']}"n";
$data .= "Content-Type: image/jpegn";
$data 。 = "コンテンツ転送エンコーディング: binarynn"; $data .= $fileContents."n";
}
$params = array('http' = > array(
'method' => 'POST', 'header' => 'Content-Type: multipart/form-data; border='.$boundary, 'content' => $data )); $ctx = stream_context_create ($params);
$fp = fopen($url, 'rb', false, $ctx);
throw new Exception("$url の問題, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("$url, $php_errormsg からのデータ読み取りの問題");
}
return $response
}
//データを設定します(この例では post から)
//サンプルデータ $postdata = array( 'name' => $_POST['name'],
'age' = > $_POST['年齢' ],
'性別' => $_POST['性別'] )//サンプル画像 $files['画像'] = $_FILES['画像']; do_post_request("http://www.jb51.net", $postdata, $files);
http://www.bkjia.com/PHPjc/322991.html

www.bkjia.com

tru​​e

http://www.bkjia.com/PHPjc/322991.html

技術記事

機能: テキスト データ ストリームを作成して返し、タイムアウト設定、プロキシ サーバー、リクエスト メソッド、fopen()、file_get_contents() などのプロセスのヘッダー情報の設定に使用できるさまざまなオプションを適用します...





声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。