php上下文是什么,php上下文(Context)介绍

php中的上下文能够用于各种文件流和数据流,能让使用者对数据的获取达到个性化的需求和更精细的控制。

举例来说,当我们想要抓取一个页面内容时,最简单直接就是使用file_get_contents方法

$html = file_get_contents('http://blog.csdn.net'); //抓取csdn博客首页

这样只局限用get方式访问,如果是post方式抓取页面貌似就办不到了,这时我们一般做法都会换用功能更强大的curl处理,其实file_get_contents也是可以使用POST方法的,方法就是使用php的上下文(Context)来控制,这里先准备一个页面来当作被抓取页面,代码很简单

使用Context:

'jerry'

);

$opts = array(

'http' => array(

'method' => 'POST',

'header' => 'Content-type: application/x-www-form-urlencoded',

'content' => http_build_query($post)

)

);

$context = stream_context_create($opts); //创建上下文对象

echo file_get_contents('http://127.0.0.1:8080/data.php', NULL, $context);

运行结果

POST: name=jerry

创建context的参数很多,opts的格式为:   $arr['wrapper']['option'] = $value,其中wrapper是支持的多种封装协议之一,目前支持以下几种:

Socket context options — Socket context option listing

HTTP context options — HTTP context option listing

FTP context options — FTP context option listing

SSL context options — SSL context option listing

CURL context options — CURL context option listing

Phar context options — Phar context option listing

MongoDB context options — MongoDB context option listing

Context parameters — Context parameter listing

Zip context options — Zip context option listing

每一种 wrapper 的 option 又不尽相同, 具体请查看手册每种wrapper支持的参数: http://php.net/manual/zh/context.php

除了创建context 时指定 $options外, 也可以创建context 后再使用 stream_context_set_option 函数设置 $options

例如:

$post = array(

'name' => 'jerry'

);

$opts = array(

'http' => array(

'method' => 'POST',

'header' => 'Content-type: application/x-www-form-urlencoded',

'content' => http_build_query($post)

)

);

$context = stream_context_create();

stream_context_set_option($context, $opts);

一个使用本地指定端口去连接服务器的例子(不指定的情况下会随机使用一个可用的端口去连接服务器):

// connect to the internet using port '7000'

$opts = array(

'socket' => array(

'bindto' => '0:7000',

),

);

// create the context...

$context = stream_context_create($opts);

// ...and use it to fetch the data

echo file_get_contents('http://www.example.com', false, $context);

That's it!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值