首页 > 语言 > PHP > 正文

php stream_context_create函数

2024-09-04 11:48:57
字体:大 中 小
来源:转载
供稿:网友

stream_context_create创建并返回一个文本数据流并应用各种选项,可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程.

函数原型:resource stream_context_create ([array $options [,array $params ]] ),看个实例:

  1. //定义options数组 
  2. $opts=array 
  3. ( 
  4.   'http'=>array 
  5.   ( 
  6.     'method'=>"get", 
  7.     'header'=>"accept-language: enrn"."cookie: foo=barrn" 
  8.   ) 
  9. ); 
  10. //创建数据流上下文 
  11. $context=stream_context_create($opts); 
  12. /*向指定地址发送http请求 
  13. 请求中包含附加的头部信息*/ 
  14. $fp=fopen('http://www.111cn.net','r',false,$context); 
  15. //输出文件指针处的所有数据 
  16. fpassthru($fp); 
  17. //关闭文件 
  18. fclose($fp); 
  19. /* 
  20. //该代码的输出结果为:即请求的cookie值 
  21. array 
  22. ( 
  23.     [foo] => bar 
  24. ) 
  25. */ 

实例二,代码如下:

  1. $default_opts=array 
  2. ( 
  3.   'http'=>array 
  4.   ( 
  5.     'method'=>"get", 
  6.     'header'=>"accept-language: enrn"."cookie: foo=bar", 
  7.     'proxy'=>"tcp://10.54.1.39:8000" 
  8.   ) 
  9. ); 
  10. $alternate_opts=array 
  11. ( 
  12.   'http'=>array 
  13.   ( 
  14.     'method'=>"post", 
  15.     'header'=>"content-type: application/x-www-form-urlencodedrn"."content-length: " . strlen("baz=bomb"), 
  16.     'content'=>"baz=bomb" 
  17.   ) 
  18. ); 
  19. $default=stream_context_get_default($default_opts); 
  20. $alternate=stream_context_create($alternate_opts); 
  21. /* sends a regular get request to proxy server at 10.54.1.39 
  22. * for www.Vevb.com using context options specified in $default_opts 
  23. */ 
  24. readfile('http://www.Vevb.com'); 
  25. /* sends a post request directly to www.Vevb.com 
  26. * using context options specified in $alternate_opts 
  27. */ 
  28. readfile('http://www.Vevb.com', false, $alternate);

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表