[php] file_get_contents를 사용하여 PHP로 데이터를 게시하는 방법은 무엇입니까?

PHP의 함수 file_get_contents()를 사용하여 URL의 내용을 가져온 다음 변수를 통해 헤더를 처리합니다 $http_response_header.

이제 문제는 일부 URL에 URL에 게시 할 데이터 (예 : 로그인 페이지)가 필요하다는 것입니다.

어떻게합니까?

stream_context를 사용하여 그렇게 할 수는 있지만 완전히 명확하지는 않습니다.

감사.



답변

를 사용하여 HTTP POST 요청을 보내는 file_get_contents것은 그리 어렵지 않습니다. 실제로 추측 한 것처럼 $context매개 변수 를 사용해야합니다 .

이 페이지의 PHP 매뉴얼에 예제가 있습니다 : HTTP context options (quoting) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

기본적으로 올바른 옵션으로 해당 스트림을 작성하고 (해당 페이지에 전체 목록이 있음) 세 번째 매개 변수로 사용하여 file_get_contents더 이상 ;-)하지 않아야합니다.

참고로 일반적으로 말하면 HTTP POST 요청을 보내기 위해 curl을 사용하는 경향이 있습니다.이 옵션은 많은 옵션을 제공하지만 스트림은 아무도 모르는 PHP의 좋은 것 중 하나입니다. .


답변

대안으로, fopen 을 사용할 수도 있습니다

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}


답변

$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}


답변