douyi5157 2013-02-19 14:01
浏览 8
已采纳

使用php发布数据[重复]

This question already has an answer here:

I want to know how to post data with php, for example get the input from the local php then write to the input with id on another webpage. I think that those are called PHP bots, but I didn't quite understand the function. If you could just show me the code, if this is possible.

UPDATE: To make it cleaner - how to "write" to an input on another page with PHP.

</div>
  • 写回答

1条回答 默认 最新

  • dtkf64283 2013-02-19 14:08
    关注

    To Post Data to an URL, you can use CURL for that.

    $my_url = 'http://www.google.com';
    $post_vars = 'postvar1=' . $postvar1 . '&postvar2=' . $postvar2;
    
    $curl = curl_init($my_url);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_vars);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    
    $response = curl_exec($curl);
    

    UPDATE

    If you don´t want to use CURL you can try it this way:

    $server= 'www.someserver.com';
    $url = '/path/to/file.php';
    $content = 'name1=value1&name2=value2';
    $content_length = strlen($content);
    $headers= "POST $url HTTP/1.0
    Content-type: text/html
    Host: $server
    Content-length: $content_length
    
    ";
    $fp = fsockopen($server, $port, $errno, $errstr);
    if (!$fp) return false;
    fputs($fp, $headers);
    fputs($fp, $content);
    $ret = "";
    while (!feof($fp)) {
    $ret.= fgets($fp, 1024);
    }
    fclose($fp);
    print $ret;
    

    and if you´re using PHP5 here's a function you can use to post data to an URL:

    function do_post_request($url, $data, $optional_headers = null)
    {
      $params = array('http' => array(
                  'method' => 'POST',
                  'content' => $data
                ));
      if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
      }
      $ctx = stream_context_create($params);
      $fp = @fopen($url, 'rb', false, $ctx);
      if (!$fp) {
        throw new Exception("Problem with $url, $php_errormsg");
      }
      $response = @stream_get_contents($fp);
      if ($response === false) {
        throw new Exception("Problem reading data from $url, $php_errormsg");
      }
      return $response;
    }
    

    this function is from here

    and to use this function do something like

    <?php
    
    do_post_request('http://search.yahoo.com/', 'p=hello+yahoo')
    
    ?>
    

    this will search for "hello yahoo"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度