복붙노트

PHP + 컬, HTTP POST 샘플 코드?

PHP

PHP + 컬, HTTP POST 샘플 코드?

누구든지 HTTP POST를 사용하여 PHP 컬을 수행하는 방법을 보여줄 수 있습니까?

이런 식으로 데이터를 보내고 싶습니다 :

username=user1, password=passuser1, gender=1

www.domain.com하려면

곱슬 곱슬이 result = OK와 같은 응답을 반환 할 것으로 기대합니다. 어떤 예가 있습니까?

해결법

  1. ==============================

    1.

    <?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 { ... }
    ?>
    
  2. ==============================

    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()));
    }
    

    여기에서 주목할 점은 getResponse () 메소드를 사용하여 AdapterInterface와 같은 일종의 인터페이스를 생성하고 위의 클래스가이를 구현하도록하는 것이 가장 좋습니다. 그런 다음 응용 프로그램에 부작용없이 항상이 구현을 다른 어댑터와 교환 할 수 있습니다.

    일반적으로 Windows 운영 체제에서 PHP의 cURL에 문제가 있습니다. https로 보호 된 엔드 포인트에 연결하는 동안 인증서 확인에 실패했음을 알리는 오류가 표시됩니다.

    대부분의 사람들이 cURL 라이브러리에 단순히 인증서 오류를 무시하고 계속하도록 명령하는 것입니다 (curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false);). 이렇게하면 코드가 작동하므로 거대한 보안 구멍이 생겨 악의적 인 사용자가 Man In The Middle 공격과 같은 다양한 공격을 수행 할 수 있습니다.

    절대로 그렇게하지 마십시오. 대신 php.ini를 수정하고 PHP 인증서가 인증서를 올바르게 확인할 수 있도록 PHP에 알려 주면됩니다.

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

    최신 cacert.pem은 인터넷에서 다운로드하거나 즐겨 찾는 브라우저에서 추출 할 수 있습니다. php.ini 관련 설정을 변경하면 웹 서버를 다시 시작해야합니다.

  3. ==============================

    3.

    이것을 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>
    

    PHP POST를 www.google.com으로 보내서 데이터를 보냈습니다.

    게시 된 변수를 읽도록 서버가 프로그래밍되어 있다면이를 기반으로 다른 작업을 수행 할 수 있습니다.

  4. ==============================

    4.

    다음과 같이 쉽게 접근 할 수 있습니다.

    <?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);
    
  5. ==============================

    5.

    양식에서 리디렉션, 인증, 쿠키, SSL (https) 또는 POST 변수를 예상하는 완전히 열려있는 스크립트 이외의 다른 것을 사용하는 경우에는 이빨을 정말 빨리 씹기 시작할 것입니다. 많은 오버 헤드를 설정할 필요성을 제거하면서 마음에있는 것을 정확히 수행하는 스누피를 살펴보십시오.

  6. ==============================

    6.

    컬 포스트 + 오류 처리 + 헤더 설정 [@ 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',
    ]);
    
  7. ==============================

    7.

    다음은 PHP + 컬에 대한 상용구 코드입니다. 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, "");
        ...
    ?>
    
  8. ==============================

    8.

    더 간단한 대답 자신의 웹 사이트에 정보를 전달하는 경우 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']);}
    
  9. ==============================

    9.

    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;
    }
    
  10. ==============================

    10.

    쿠키로 사이트에 로그인하려고 시도하는 경우.

    이 코드 :

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

    많은 사이트가 상태 200을 반환하기 때문에 로그인하려고하면 작동하지 않을 수 있지만 게시물이 성공적이지 않습니다.

    로그인 게시물이 성공적인지 확인하는 쉬운 방법은 쿠키를 다시 설정하는지 확인하는 것입니다. 출력물에 Set-Cookies 문자열이 있으면 게시물이 성공적이지 않고 새로운 세션이 시작됨을 의미합니다.

    또한 게시물이 성공적 일 수 있지만 상태는 200 대신 리디렉션 될 수 있습니다.

    게시물이 성공적인지 확인하려면 다음을 시도하십시오.

    소식 뒤에 위치를 따라 가면 소식이 리디렉션되는 페이지로 이동합니다.

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    

    그리고 요청에 새로운 쿠키가 있는지 확인하는 것보다 :

    if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output)) 
    
    {echo 'post successful'; }
    
    else { echo 'not successful'; }
    
  11. from https://stackoverflow.com/questions/2138527/php-curl-http-post-sample-code by cc-by-sa and MIT lisence