首页 文章

PHP curl,HTTP POST示例代码?

提问于
浏览
381

任何人都可以告诉我如何使用HTTP POST进行PHP卷曲吗?

我想发送这样的数据:

username=user1, password=passuser1, gender=1

www.domain.com

我希望curl返回像 result=OK 这样的响应 . 有什么例子吗?

10 回答

  • 194

    如果表单使用重定向,身份验证,cookie,SSL(https)或除了期望POST变量的完全开放脚本以外的任何其他内容,您将开始快速咬牙切齿 . 看一下Snoopy,它可以完全满足您的需求,同时无需设置大量开销 .

  • 2

    如果您尝试使用cookie登录网站 .

    这段代码:

    if ($server_output == "OK") { ... } else { ... }
    

    如果您尝试登录可能无效,因为许多站点返回状态200,但帖子不成功 .

    检查登录帖是否成功的简便方法是检查是否再次设置cookie . 如果在输出中具有Set-Cookies字符串,则表示帖子不成功并且它启动新会话 .

    帖子也可以成功,但状态可以重定向200 .

    为了确保帖子成功,试试这个:

    在帖子之后关注位置,因此它将转到帖子重定向到的页面:

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    

    而不是检查请求中是否存在新的cookie:

    if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output)) 
    
    {echo 'post successful'; }
    
    else { echo 'not successful'; }
    
  • 646
    curlPost('google.com', [
        'username' => 'admin',
        'password' => '12345',
    ]);
    
    
    function curlPost($url, $data) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $response = curl_exec($ch);
        if (curl_error($ch)) {
            throw new \Exception(curl_error($ch));
        }
        curl_close($ch);
    
        return $response;
    }
    
  • 3

    卷曲后错误处理设置 Headers [感谢@ mantas-d]:

    function curlPost($url, $data=NULL, $headers = NULL) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        if(!empty($data)){
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
    
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
    
        $response = curl_exec($ch);
    
        if (curl_error($ch)) {
            trigger_error('Curl Error:' . curl_error($ch));
        }
    
        curl_close($ch);
        return $response;
    }
    
    
    curlPost('google.com', [
        'username' => 'admin',
        'password' => '12345',
    ]);
    
  • 18

    使用php curl_exec执行HTTP帖子的实例:

    把它放在一个名为foobar.php的文件中:

    <?php
      $ch = curl_init();
      $skipper = "luxury assault recreational vehicle";
      $fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash');
      $postvars = '';
      foreach($fields as $key=>$value) {
        $postvars .= $key . "=" . $value . "&";
      }
      $url = "http://www.google.com";
      curl_setopt($ch,CURLOPT_URL,$url);
      curl_setopt($ch,CURLOPT_POST, 1);                //0 for a get request
      curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
      curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
      curl_setopt($ch,CURLOPT_TIMEOUT, 20);
      $response = curl_exec($ch);
      print "curl response is:" . $response;
      curl_close ($ch);
    ?>
    

    然后使用命令 php foobar.php 运行它,它将这种输出转储到屏幕:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title</title>
    
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <body>
      A mountain of content...
    </body>
    </html>
    

    所以你向www.google.com做了一个PHP POST并发送了一些数据 .

    如果服务器被编程为读取后变量,它可以决定基于此做一些不同的事情 .

  • 2
    <?php
    //
    // A very simple PHP example that sends a HTTP POST to a remote site
    //
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
                "postvar1=value1&postvar2=value2&postvar3=value3");
    
    // In real life you should use something like:
    // curl_setopt($ch, CURLOPT_POSTFIELDS, 
    //          http_build_query(array('postvar1' => 'value1')));
    
    // Receive server response ...
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $server_output = curl_exec($ch);
    
    curl_close ($ch);
    
    // Further processing ...
    if ($server_output == "OK") { ... } else { ... }
    ?>
    
  • 5

    可以通过以下方式轻松达到:

    <?php
    
    $post = [
        'username' => 'user1',
        'password' => 'passuser1',
        'gender'   => 1,
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    $response = curl_exec($ch);
    var_export($response);
    
  • 2

    程序

    // set post fields
    $post = [
        'username' => 'user1',
        'password' => 'passuser1',
        'gender'   => 1,
    ];
    
    $ch = curl_init('http://www.example.com');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    
    // execute!
    $response = curl_exec($ch);
    
    // close the connection, release resources used
    curl_close($ch);
    
    // do anything you want with your response
    var_dump($response);
    

    面向对象

    <?php
    namespace MyApp\Http;
    
    class Curl
    {
        /** @var resource cURL handle */
        private $ch;
    
        /** @var mixed The response */
        private $response = false;
    
        /**
         * @param string $url
         * @param array  $options
         */
        public function __construct($url, array $options = array())
        {
            $this->ch = curl_init($url);
    
            foreach ($options as $key => $val) {
                curl_setopt($this->ch, $key, $val);
            }
    
            curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        }
    
        /**
         * Get the response
         * @return string
         * @throws \RuntimeException On cURL error
         */
        public function getResponse()
        {
             if ($this->response) {
                 return $this->response;
             }
    
            $response = curl_exec($this->ch);
            $error    = curl_error($this->ch);
            $errno    = curl_errno($this->ch);
    
            if (is_resource($this->ch)) {
                curl_close($this->ch);
            }
    
            if (0 !== $errno) {
                throw new \RuntimeException($error, $errno);
            }
    
            return $this->response = $response;
        }
    
        /**
         * Let echo out the response
         * @return string
         */
        public function __toString()
        {
            return $this->getResponse();
        }
    }
    
    // usage
    $curl = new \MyApp\Http\Curl('http://www.example.com', array(
        CURLOPT_POSTFIELDS => array('username' => 'user1')
    ));
    
    try {
        echo $curl;
    } catch (\RuntimeException $ex) {
        die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode()));
    }
    

    请注意:最好创建一种名为 AdapterInterface 的接口,例如使用 getResponse() 方法,让上面的类实现它 . 然后,您始终可以将此实现与您喜欢的另一个适配器交换,而不会对您的应用程序产生任何副作用 .

    使用HTTPS /加密流量

    通常在Windows操作系统下,PHP中的cURL存在问题 . 在尝试连接到受https保护的 endpoints 时,您将收到一条错误消息,告诉您 certificate verify failed .

    大多数人在这里做的是告诉cURL库简单地忽略证书错误并继续( curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); ) . 由于这将使您的代码工作,您将引入巨大的安全漏洞并使恶意用户能够对您的应用程序执行各种攻击,如Man In The Middle攻击等 .

    从来没有这样做过 . 相反,您只需要修改 php.ini 并告诉PHP CA Certificate 文件在哪里让它正确验证证书:

    ; modify the absolute path to the cacert.pem file
    curl.cainfo=c:\php\cacert.pem
    

    最新的 cacert.pem 可以从Internet或extracted from your favorite browser下载 . 更改任何 php.ini 相关设置时,请记住重新启动您的网络服务器 .

  • 25

    以下是PHP curl的一些样板代码http://www.webbotsspidersscreenscrapers.com/DSP_download.php

    包含在这些库中将简化开发

    <?php
    # Initialization
    include("LIB_http.php");
    include("LIB_parse.php");
    $product_array=array();
    $product_count=0;
    
    # Download the target (store) web page
    $target = "http://www.tellmewhenitchanges.com/buyair";
    $web_page = http_get($target, "");
        ...
    ?>
    
  • 5

    更简单的答案如果您将信息传递到您自己的网站,则使用SESSION变量 . 开始php页面:

    session_start();
    

    如果在某些时候,您希望在PHP中生成信息并传递到会话中的下一页,而不是使用POST变量,请将其分配给SESSION变量 . 例:

    $_SESSION['message']='www.'.$_GET['school'].'.edu was not found.  Please try again.'
    

    然后在下一页上,您只需引用此SESSION变量 . 注意:使用它之后,请确保将其销毁,因此在使用后它不会持久存在:

    if (isset($_SESSION['message'])) {echo $_SESSION['message']; unset($_SESSION['message']);}
    

相关问题