这篇文章主要介绍了关于实现PHP使用file_get_contents发送http请求功能简单,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

本文实例讲述了PHP使用file_get_contents发送http请求功能。分享给大家供大家参考,具体如下:

服务器端模拟 POST/GET 等请求,使用 CURL 很容易办到(例如前面一篇《php使用CURL模拟GET与POST向微信接口提交及获取数据的方法》),那么如果不使用 CURL 库,又该怎么办呢?

$data = array(
  'test'=>'bar',
  'baz'=>'boom',
  'site'=>'www.nimip.com',
  'name'=>'nimip.com');
$data = http_build_query($data);
//$postdata = http_build_query($data);
$options = array(
  'http' => array(
    'method' => 'POST',
    'header' => 'Content-type:application/x-www-form-urlencoded',
    'content' => $data
    'timeout' => 60 // 超时时间(单位:s)
  )
);
$url = "http://www.testweb.com";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
登录后复制

其中http://www.testweb.com的代码为:

$data = $_POST;
print_r( $data );
登录后复制

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

相关推荐:

PHP使用new StdClass()创建空对象的方法分析

php使用gearman进行任务分发

以上就是PHP使用file_get_contents发送http请求功能简单的详细内容,更多请关注Work网其它相关文章!

09-15 14:25