zoukankan      html  css  js  c++  java
  • 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
    ".
                   "Content-length:".strlen($data)."
    " .
                   "Cookie: foo=bar
    " .
                   "
    ",
         '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);
    ?>
  • 相关阅读:
    全区停水,测什么时候来水。
    和电脑打国标麻将,一定要注意
    这是一个可怕的交易
    起一卦,还是这样。什么时候能好起来。
    Linux内核源码真是个好东西
    命宫——天机化忌
    bzoj1024[SCOI2009]生日快乐
    bzoj2561最小生成树
    bzoj2423[HAOI2010]最长公共子序列
    bzoj2705[SDOI2012]Longge的问题
  • 原文地址:https://www.cnblogs.com/zhanghanwen16/p/8529398.html
Copyright © 2011-2022 走看看