php 基础 获取远程连接

1 file_get_contents get

$opts = array(
  'http'=>array(
    'method'=>"GET",
    'timeout'=>10,
  )
);
$context = stream_context_create($opts);
$html =file_get_contents('http://www.example.com', false, $context);
echo $html;

1.2 file_get_contents post

<?php
 $data = array("name" => 'test_name',"content" => 'test_con');
 $data = http_build_query($data);
 $opts = array(
   'http'=>array(
     'method'=>"POST",
     'header'=>"Content-type: application/x-www-form-urlencoded\r\n".
               "Content-length:".strlen($data)."\r\n" .
               "Cookie: foo=bar\r\n" .
               "\r\n",
     'content' => $data,
   )
 );
 $cxContext = stream_context_create($opts);
 $sFile = file_get_contents("http://127.0.0.1/reponse.php", false, $cxContext);  
 echo $sFile;
?>

2 使用curl,get获取数据

<?php
$url = 'http://www.example.com';
//初始化一个 cURL 对象
$ch  = curl_init();
//设置你需要抓取的URL
curl_setopt($ch, CURLOPT_URL, $url);
// 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//是否获得跳转后的页面
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
?>

2.2 使用curl。post获取数据

<?php
function curl_post($url, $arr_data){
   $post_data = http_build_query($url_data);
   $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch,  CURLOPT_POSTFLELDS, $post_data);
    $data = curl_exec($ch);
    curl_close($ch);
    echo $data;
}
$arr_post = array(
    'name'=>'test_name',
    'age'   => 1
);
curl_post("http://www.explame.com/", $arr_post);
?>

 

posted @ 2018-03-08 16:49  zhw15  阅读(212)  评论(0编辑  收藏  举报