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

실제로 검색이 끝나면 내용을 읽고 싶습니다. 문제는 URL이 POST메소드 만 허용하며 메소드에 대한 조치를 취하지 않는다는 것입니다 GET.

domdocument또는 의 도움으로 모든 내용을 읽어야합니다 file_get_contents(). 메소드를 사용하여 매개 변수를 보내고 POST내용을 통해 읽을 수있는 방법이 PHP있습니까?



답변

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 매뉴얼을 참조하십시오.


답변

cURL을 사용할 수 있습니다 :

<?php
//The url you wish to send the POST request to
$url = $file_name;

//The data you want to send via POST
$fields = [
    '__VIEWSTATE '      => $state,
    '__EVENTVALIDATION' => $valid,
    'btnSubmit'         => 'Submit'
];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//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, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 

//execute post
$result = curl_exec($ch);
echo $result;
?>


답변

curl을 사용하여 데이터를 게시하려면 다음 함수를 사용하십시오. $ 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 ()를 사용합니다.


답변

전체 단위 테스트를 거쳤으며 최신 코딩 방법 을 사용하는 오픈 소스 패키지 구슬 을 사용하는 것이 좋습니다 .

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


답변

그렇게하면 다른 CURL 메소드가 있습니다.

PHP curl 확장 프로그램이 작동하는 방식을 이해하고 setopt () 호출과 다양한 플래그를 결합하면 간단합니다. 이 예제에는 $ xml 변수가 있는데,이 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의 반환 값으로 출력을 제공하도록 curl에 지시합니다. 그런 다음 전화를 걸고 연결을 닫습니다. 결과는 $ response입니다.


답변

우연히 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 루트의 격리 된 PHP 파일에서 다음을 수행하면됩니다.

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

// ... your code

테마를 표시하거나 HTML을 출력하지 않으며 WordPress API로 해킹하십시오!


답변

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

개량

  • http_build_query를 사용하여 request-array에서 query-string을 가져옵니다 (배열 자체를 사용할 수도 있으므로 http://php.net/manual/en/function.curl-setopt.php 참조 ).
  • 반향 대신 응답을 반환합니다. 그러나 curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true); 줄을 제거하여 반환을 피할 수 있습니다 . . 그 후 리턴 값은 부울 (true = 요청이 성공하면 오류가 발생 함)이며 응답이 에코됩니다. 참조 : http://php.net/en/manual/function.curl-exec.php
  • curl_close 를 사용하여 curl 처리기의 세션 종료 및 삭제를 정리하십시오 . 참조 : http://php.net/manual/en/function.curl-close.php
  • curl_setopt 함수에 부울 값을 사용하는 대신 임의의 숫자를 사용하십시오. (제로가 아닌 숫자도 true로 간주되지만 true를 사용하면 더 읽기 쉬운 코드가 생성되지만 이는 제 의견입니다)
  • HTTP-PUT / DELETE 호출 기능 (RESTful 서비스 테스트에 유용)

사용 예

가져 오기

$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}]');
    }
}