Apache HTTP 서버의 경우 htpasswd를 이용하여 간단한 아이디/패스워드 인증을 도입 가능함
이것을 basic authentication이라고 부름
참고: http://httpd.apache.org/docs/current/programs/htpasswd.html
웹 브라우저의 경우, 아이디와 패스워드를 입력하는 창이 뜨기 때문에 그 창에 직접 입력하면 되지만, headless browser나 커맨드라인 웹 클라이언트의 경우에는 http request header에 실어서 보내야 해당 웹페이지에 접근이 가능함
PHP로 request header를 전송하는 방법을 살펴보고 basic authentication 정보를 보내는 방법을 기술해 봄
우선 사용자 아이디와 패스워드를 :로 이어붙이고 base64 인코드를 해서 인코드된 인증 문자열을 만들어냄
$encoded_credential = base64_encode($userid . ":" . $passwd);
GET/POST 메소드를 결정하고 헤더를 다음과 같은 포맷으로 이어붙여서 전송함
이어붙일 때 반드시 carriage return과 newline을 라인마다 붙여야 함(\r\n)
stream_context_create로 컨텍스트를 만들어야 request header를 보낼 수 있음
$opts = array('http' => array('method' => 'GET',
'header' => "Authorization: Basic $encoded_credential\\r\
Accept-Encoding: gzip,deflate,sdch\\r\
User-Agent: $ua_str\\r\
$cookie_str",
'timeout' => '1'));
$context = stream_context_create($opts);
fopen으로 웹 서버에 접속해서 헤더를 전송하고 웹페이지 HTML을 받아옴
fopen의 파라미터로 컨텍스트가 넘겨짐
// fetch the html from url
$fp = fopen($url, "r", false, $context);
if (!$fp) {
print "Error: can't read the rank data from '$url'\n";
return -1;
}
$html_arr = array();
while (!feof($fp)) {
$line = fread($fp, $block_size);
array_push($html_arr, $line);
}
fclose($fp);
추가로 gzip으로 압축해서 서버가 응답한 경우, gzdecode를 이용해서 압축을 풀어야 함
$html = gzdecode(implode($html_arr));
압축 여부는 response header를 살펴보거나 HTML의 일부 바이트를 살펴보는 방법이 있으나 여기서는 구현하지 않았음