복붙노트

PHP로 POST 요청을 보내려면 어떻게해야합니까?

PHP

PHP로 POST 요청을 보내려면 어떻게해야합니까?

사실 나는 그것이 끝나면 검색 쿼리 다음에 오는 내용을 읽고 싶다. 문제는 URL이 POST 메서드 만 허용한다는 것이며 GET 메서드로 어떤 동작도 취하지 않는다는 것입니다.

domdocument 또는 file_get_contents ()를 사용하여 모든 내용을 읽어야합니다. POST 메서드로 매개 변수를 보내고 PHP를 통해 내용을 읽을 수있는 메서드가 있습니까?

해결법

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

    1.

    PHP5를 사용하는 CURL-less 메소드 :

    $url = 'http://server.com/path';
    $data = array('key1' => 'value1', 'key2' => 'value2');
    
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) { /* Handle error */ }
    
    var_dump($result);
    

    메서드와 헤더를 추가하는 방법에 대한 자세한 내용은 PHP 매뉴얼을 참조하십시오. 예를 들면 다음과 같습니다.

  2. ==============================

    2.

    나는 이걸 시도해 봤는데 ... 괜찮 았어.

    <?php
    $url = $file_name;
    $fields = array(
                '__VIEWSTATE'=>urlencode($state),
                '__EVENTVALIDATION'=>urlencode($valid),
                'btnSubmit'=>urlencode('Submit')
            );
    
    //url-ify the data for the POST
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    $fields_string = rtrim($fields_string,'&');
    
    //open connection
    $ch = curl_init();
    
    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    
    //execute post
    $result = curl_exec($ch);
    print $result;
    ?>
    
  3. ==============================

    3.

    다음 함수를 사용하여 컬을 사용하여 데이터를 게시합니다. $ data는 게시 할 필드 배열입니다 (http_build_query를 사용하여 올바르게 인코딩됩니다). 데이터는 application / x-www-form-urlencoded를 사용하여 인코딩됩니다.

    function httpPost($url, $data)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    

    @Edward는 curl이 CURLOPT_POSTFIELDS 매개 변수에 전달 된 배열을 올바르게 인코딩하므로 http_build_query가 생략 될 수 있다고 언급하지만이 경우 데이터는 multipart / form-data를 사용하여 인코딩됩니다.

    필자는 application / x-www-form-urlencoded를 사용하여 데이터를 인코딩 할 것으로 기대하는 API와 함께이 함수를 사용합니다. 그래서 http_build_query ()를 사용합니다.

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

    4.

    완전히 테스트 된 오픈 소스 패키지 그램을 사용하고 최신 코딩 방법을 사용하는 것이 좋습니다.

    Guzzle 설치하기

    프로젝트 폴더의 명령 줄로 이동하여 다음 명령을 입력하십시오 (패키지 관리자 작성기가 이미 설치되어 있다고 가정). Composer 설치 방법에 대한 도움이 필요하면 여기를 살펴보십시오.

    php composer.phar require guzzlehttp/guzzle
    

    Guzzle을 사용하여 POST 요청 보내기

    Guzzle의 사용법은 경량의 객체 지향 API를 사용하므로 매우 간단합니다.

    // Initialize Guzzle client
    $client = new GuzzleHttp\Client();
    
    // Create a POST request
    $response = $client->request(
        'POST',
        'http://example.org/',
        [
            'form_params' => [
                'key1' => 'value1',
                'key2' => 'value2'
            ]
        ]
    );
    
    // Parse the response object, e.g. read the headers, body, etc.
    $headers = $response->getHeaders();
    $body = $response->getBody();
    
    // Output headers and body for debugging purposes
    var_dump($headers, $body);
    
  5. ==============================

    5.

    당신이 그런 식으로가는 경우 또 다른 CURL 방법이 있습니다.

    이것은 일단 PHP curl 확장이 작동하는 방식으로 머리를 터뜨리면 다양한 플래그를 setopt () 호출과 결합하여 매우 간단합니다. 이 예제에서 나는 보낼 준비가 된 XML을 가지고있는 변수 $ xml을 얻었습니다. 그 내용을 예제의 테스트 메소드에 게시 할 것입니다.

    $url = 'http://api.example.com/services/xmlrpc/';
    $ch = curl_init($url);
    
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    //process $response
    

    먼저 연결을 초기화 한 다음 setopt ()를 사용하여 몇 가지 옵션을 설정합니다. 이것들은 PHP에게 우리가 게시물 요청을하고 있고, 데이터를 제공하면서 데이터를 보내고 있다고 알려줍니다. CURLOPT_RETURNTRANSFER 플래그는 curl이 출력하지 않고 curl_exec의 반환 값으로 출력하도록 알려줍니다. 그런 다음 호출을하고 연결을 닫습니다. 결과는 $ response에 있습니다.

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

    6.

    혹시라도 Wordpress를 사용하여 응용 프로그램을 개발한다면 (실제로는 매우 간단한 자료라도 권한 부여, 정보 페이지 등을 얻을 수있는 편리한 방법입니다) 다음 코드 조각을 사용할 수 있습니다.

    $response = wp_remote_post( $url, array('body' => $parameters));
    
    if ( is_wp_error( $response ) ) {
        // $response->get_error_message()
    } else {
        // $response['body']
    }
    

    웹 서버에서 사용할 수있는 내용에 따라 실제 HTTP 요청을 만드는 다양한 방법을 사용합니다. 자세한 내용은 HTTP API 설명서를 참조하십시오.

    Wordpress 엔진을 시작하기위한 커스텀 테마 나 플러그인을 개발하고 싶지 않다면, wordpress root에있는 고립 된 PHP 파일에서 다음과 같이하면됩니다 :

    require_once( dirname(__FILE__) . '/wp-load.php' );
    
    // ... your code
    

    Wordpress API를 사용하여 테마 나 출력물을 표시하지 않습니다.

  7. ==============================

    7.

    컬 (Fred Tanrikut)의 대답에 대한 몇 가지 생각을 덧붙이고 싶습니다. 위의 답변에 대부분이 이미 적혀 있지만, 모두 함께 포함 된 답변을 제시하는 것이 좋습니다.

    다음은 응답 본문과 관련된 컬 (curl)을 기반으로 HTTP-GET / POST / PUT / DELETE 요청을하기 위해 작성한 클래스입니다.

    class HTTPRequester {
        /**
         * @description Make HTTP-GET call
         * @param       $url
         * @param       array $params
         * @return      HTTP-Response body or an empty string if the request fails or is empty
         */
        public static function HTTPGet($url, array $params) {
            $query = http_build_query($params); 
            $ch    = curl_init($url.'?'.$query);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            $response = curl_exec($ch);
            curl_close($ch);
            return $response;
        }
        /**
         * @description Make HTTP-POST call
         * @param       $url
         * @param       array $params
         * @return      HTTP-Response body or an empty string if the request fails or is empty
         */
        public static function HTTPPost($url, array $params) {
            $query = http_build_query($params);
            $ch    = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
            $response = curl_exec($ch);
            curl_close($ch);
            return $response;
        }
        /**
         * @description Make HTTP-PUT call
         * @param       $url
         * @param       array $params
         * @return      HTTP-Response body or an empty string if the request fails or is empty
         */
        public static function HTTPPut($url, array $params) {
            $query = \http_build_query($params);
            $ch    = \curl_init();
            \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
            \curl_setopt($ch, \CURLOPT_HEADER, false);
            \curl_setopt($ch, \CURLOPT_URL, $url);
            \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'PUT');
            \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
            $response = \curl_exec($ch);
            \curl_close($ch);
            return $response;
        }
        /**
         * @category Make HTTP-DELETE call
         * @param    $url
         * @param    array $params
         * @return   HTTP-Response body or an empty string if the request fails or is empty
         */
        public static function HTTPDelete($url, array $params) {
            $query = \http_build_query($params);
            $ch    = \curl_init();
            \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
            \curl_setopt($ch, \CURLOPT_HEADER, false);
            \curl_setopt($ch, \CURLOPT_URL, $url);
            \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'DELETE');
            \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
            $response = \curl_exec($ch);
            \curl_close($ch);
            return $response;
        }
    }
    
    $response = HTTPRequester::HTTPGet("http://localhost/service/foobar.php", array("getParam" => "foobar"));
    
    $response = HTTPRequester::HTTPPost("http://localhost/service/foobar.php", array("postParam" => "foobar"));
    
    $response = HTTPRequester::HTTPPut("http://localhost/service/foobar.php", array("putParam" => "foobar"));
    
    $response = HTTPRequester::HTTPDelete("http://localhost/service/foobar.php", array("deleteParam" => "foobar"));
    

    이 간단한 클래스를 사용하여 멋진 서비스 테스트를 수행 할 수도 있습니다.

    class HTTPRequesterCase extends TestCase {
        /**
         * @description test static method HTTPGet
         */
        public function testHTTPGet() {
            $requestArr = array("getLicenses" => 1);
            $url        = "http://localhost/project/req/licenseService.php";
            $this->assertEquals(HTTPRequester::HTTPGet($url, $requestArr), '[{"error":false,"val":["NONE","AGPL","GPLv3"]}]');
        }
        /**
         * @description test static method HTTPPost
         */
        public function testHTTPPost() {
            $requestArr = array("addPerson" => array("foo", "bar"));
            $url        = "http://localhost/project/req/personService.php";
            $this->assertEquals(HTTPRequester::HTTPPost($url, $requestArr), '[{"error":false}]');
        }
        /**
         * @description test static method HTTPPut
         */
        public function testHTTPPut() {
            $requestArr = array("updatePerson" => array("foo", "bar"));
            $url        = "http://localhost/project/req/personService.php";
            $this->assertEquals(HTTPRequester::HTTPPut($url, $requestArr), '[{"error":false}]');
        }
        /**
         * @description test static method HTTPDelete
         */
        public function testHTTPDelete() {
            $requestArr = array("deletePerson" => array("foo", "bar"));
            $url        = "http://localhost/project/req/personService.php";
            $this->assertEquals(HTTPRequester::HTTPDelete($url, $requestArr), '[{"error":false}]');
        }
    }
    
  8. ==============================

    8.

    나는 비슷한 문제를 찾고 있었고 더 나은 접근법을 발견했다. 그래서 여기에 그것은 간다.

    리디렉션 페이지 (page1.php)에 다음 줄을 넣으면됩니다.

    header("Location: URL", TRUE, 307); // Replace URL with to be redirected URL, e.g. final.php
    

    REST API 호출에 대한 POST 요청을 리디렉션해야합니다. 이 솔루션은 사용자 정의 헤더 값뿐만 아니라 사후 데이터로 리디렉션 할 수 있습니다.

    다음은 참조 링크입니다.

  9. ==============================

    9.

    위의 curl-less 메서드의 또 다른 대안은 네이티브 스트림 함수를 사용하는 것입니다.

    이것들을 가진 POST 함수는 간단히 다음과 같이 될 수 있습니다 :

    <?php
    
    function post_request($url, array $params) {
      $query_content = http_build_query($params);
      $fp = fopen($url, 'r', FALSE, // do not use_include_path
        stream_context_create([
        'http' => [
          'header'  => [ // header array does not need '\r\n'
            'Content-type: application/x-www-form-urlencoded',
            'Content-Length: ' . strlen($query_content)
          ],
          'method'  => 'POST',
          'content' => $query_content
        ]
      ]));
      if ($fp === FALSE) {
        fclose($fp);
        return json_encode(['error' => 'Failed to get contents...']);
      }
      $result = stream_get_contents($fp); // no maxlength/offset
      fclose($fp);
      return $result;
    }
    
  10. ==============================

    10.

    당신이 사용할 수있는 것이 하나 더 있습니다.

    <?php
    $fields = array(
        'name' => 'mike',
        'pass' => 'se_ret'
    );
    $files = array(
        array(
            'name' => 'uimg',
            'type' => 'image/jpeg',
            'file' => './profile.jpg',
        )
    );
    
    $response = http_post_fields("http://www.example.com/", $fields, $files);
    ?>
    

    자세한 내용을 보려면 여기를 클릭하십시오.

  11. ==============================

    11.

    POST 요청을 쉽게 보내려면 PEAR의 HTTP_Request2 패키지를 사용해보십시오. 또는 PHP의 컬 기능을 사용하거나 PHP 스트림 컨텍스트를 사용할 수 있습니다.

    HTTP_Request2를 사용하면 서버를 조롱 할 수 있으므로 코드를 쉽게 단위 테스트 할 수 있습니다.

  12. from https://stackoverflow.com/questions/5647461/how-do-i-send-a-post-request-with-php by cc-by-sa and MIT lisence