이 문서의 예에서는 PHP가 stream_context_create()를 사용하여 POST/GET 요청을 시뮬레이션하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.
때로는 서버 측에서 POST/GET 및 기타 요청을 시뮬레이션해야 합니다. 즉, PHP 프로그램에서 시뮬레이션을 구현하는 방법입니다. 그것을 하기 위해? 즉, PHP 프로그램에서 배열이 주어지면 이 배열을 다른 주소로 어떻게 POST/GET합니까? 물론 CURL을 사용하면 쉽지만, CURL 라이브러리를 사용하지 않는다면 어떻게 될까요? 사실 PHP에는 이미 관련 함수가 구현되어 있는데, 이 함수가 다음에 이야기할 stream_context_create() 입니다.
코드를 직접 보여주세요. 이것이 가장 좋은 방법입니다.
$data = array( 'foo'=>'bar', 'baz'=>'boom', 'site'=>'localhost', 'name'=>'nowa magic'); $data = http_build_query($data); //$postdata = http_build_query($data); $options = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $data //'timeout' => 60 * 60 // 超时时间(单位:s) ) ); $url = "http://localhost/test2.php"; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); echo $result;
http://localhost/test2.php의 코드는 다음과 같습니다.
$data = $_POST; echo '<pre class="brush:php;toolbar:false">'; print_r( $data ); echo '';
실행 결과는 다음과 같습니다.
Array ( [foo] => bar [baz] => boom [site] => localhost [name] => nowa magic )
설명할 핵심 사항:
1. 위 프로그램은 http_build_query() 함수를 사용합니다. 자세한 내용은 이전 기사 "PHP가 http_build_query()를 사용하여 URL 문자열을 구성하는 방법"을 참조하세요.
2. stream_context_create()는 POST를 통한 액세스, 프록시 사용, 헤더 전송 등과 같은 파일 열기를 위한 컨텍스트 옵션을 생성하는 데 사용됩니다. 스트림을 생성하고 다른 예를 들어보겠습니다.
$context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)). "Content-type: application/x-www-form-urlencoded\r\n", 'content' => http_build_query(array('status' => $message)), 'timeout' => 5, ), )); $ret = file_get_contents('http://twitter.com/statuses/update.xml', false, $context);
$opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ) ); //创建数据流上下文 $context = stream_context_create($opts); $html =file_get_contents('http://localhost', false, $context); //fopen输出文件指针处的所有剩余数据: //fpassthru($fp); //fclose()前使用