A note on how to deal with Cookies
To receive a cookie:
$httphandle = fopen($url,"r");
$meta = stream_get_meta_data($httphandle);
for ($j = 0; isset($meta['wrapper_data'][$j]); $j++) {
$httpline = $meta['wrapper_data'][$j];
@list($header,$parameters) = explode(";",$httpline,2);
@list($attr,$value) = explode(":",$header,2);
if (strtolower(trim($attr)) == "set-cookie") {
$cookie = trim($value);
break;
}
}
fclose($httphandle);
echo $cookie;
To send a cookie:
$user_agent = ini_get("user_agent");
ini_set("user_agent",$user_agent . "\r\nCookie: " . $cookie);
$httphandle = fopen($url,"r");
fclose($httphandle);
ini_set("user_agent",$user_agent);
HTTP 와 HTTPS
PHP 4, PHP 5, PHP 6. PHP 4.3.0부터 https://
- http://example.com
- http://example.com/file.php?var1=val1&var2=val2
- http://user:password@example.com
- https://example.com
- https://example.com/file.php?var1=val1&var2=val2
- https://user:password@example.com
HTTP GET 방식을 사용하여, HTTP 1.0으로 파일/자원에 읽기 전용 권한을 허용합니다. 이름 기반 가상 호스트를 처리하기 위해서 Host: 헤더를 전송합니다. ini 파일이나 스트림 환경을 사용하여 user_agent 문자열을 설정하면, 요청에 같이 포함합니다.
SSL을 사용할 때, 마이크로소프트 IIS는 close_notify 식별자를 보내지 않은채 접속을 종료하는 프로토콜 오류가 있습니다. PHP는 데이터의 마지막에 도달했을때, 이를 "SSL: Fatal Protocol Error"로 보고합니다. 이를 처리하기 위해서는 error_reporting 레벨에 경고를 포함하지 않도록 해야합니다. PHP 4.3.7 이후는 https:// 래퍼를 통해 스트림을 열 때, 문제가 있는 IIS 서버 소프트웨어를 검출하여 경고를 하지 않습니다. ssl:// 소켓을 만들기 위해 fsockopen()을 사용한다면, 경고를 직접 검출하여 없애야 합니다.
리다이렉트(Redirect)는 PHP 4.0.5부터 지원합니다; 이전 버전을 사용한다면 URL의 마지막에 슬래시를 포함해야 합니다. (모든 리다이렉트를 처리한 에후) 문서가 어떤 URL 오는지 파악해야 한다면, 스트림을 통해 반환하는 응답 헤더를 처리해야 합니다.
<?php
$url = 'http://www.example.com/redirecting_page.php';
$fp = fopen($url, 'r');
/* PHP 4.3.0 이전은 stream_get_meta_data()
대신 $http_response_header를 사용하십시오 */
$meta_data = stream_get_meta_data($fp);
foreach($meta_data['wrapper_data'] as $response) {
/* 어디로 리다이렉트합니까? */
if (substr(strtolower($response), 0, 10) == 'location: ') {
/* 리다이렉트 되는 곳으로 $url을 갱신합니다 */
$url = substr($response, 18);
}
}
?>
스트림은 리소스의 body에 접속할 권한이 있다; 헤더는 $http_response_header 변수에 저장된다. PHP 4.3.0 이후부터, 헤더는 stream_get_meta_data()를 사용하여 이용가능하다.
HTTP 접속은 읽기-전용이다; HTTP 리소스에 데이터를 쓰거나 파일을 복사할수 없다.
Note: HTTPS는 PHP 4.3.0부터 지원되었다. OpenSSL에 대한 지원 옵션으로 컴파일해야 한다.
| 속성 | 지원 |
|---|---|
| allow_url_fopen으로 제한 | 네 |
| 읽기 허용 | 네 |
| 쓰기 허용 | 아니오 |
| 추가 허용 | 아니오 |
| 동시 읽기/쓰기 허용 | N/A |
| stat() 지원 | 아니오 |
| unlink() 지원 | 아니오 |
| rename() 지원 | 아니오 |
| mkdir() 지원 | 아니오 |
| rmdir() 지원 | 아니오 |
버전 5 이전에서, HTTP 요청에 사용자 헤더를 보내기 위해서는 user_agent INI 설정의 부작용을 이용해야 합니다. user_agent에 유효한 문자열(기본 PHP/version 설정 등)을 설정하고, CR/LF를 넣은 후 추가 헤더를 넣었습니다. 이 방법은 PHP 4와 이후의 모든 버전에서 작동합니다.
Example #1 HTTP 요청에 사용자 헤더 전송하기
<?php
ini_set('user_agent', "PHP\r\nX-MyCustomHeader: Foo");
$fp = fopen('http://www.example.com/index.php', 'r');
?>
위 결과로 보내지는 요청은:
GET /index.php HTTP/1.0 Host: www.example.com User-Agent: PHP X-MyCustomHeader: Foo
HTTP 와 HTTPS
26-Jun-2008 08:17
24-Oct-2007 07:27
just an FYI about digest authentication.
While one of the above http examples has the username and password info supplied with the url, this must only be for basic authentication. it does not appear to work for digest authentication. you have to handle the digest followup request on your own.
30-Jul-2007 08:06
HTTP post function;
<?php
function post_it($datastream, $url) {
$url = preg_replace("@^http://@i", "", $url);
$host = substr($url, 0, strpos($url, "/"));
$uri = strstr($url, "/");
$reqbody = "";
foreach($datastream as $key=>$val) {
if (!empty($reqbody)) $reqbody.= "&";
$reqbody.= $key."=".urlencode($val);
}
$contentlength = strlen($reqbody);
$reqheader = "POST $uri HTTP/1.1\r\n".
"Host: $host\n". "User-Agent: PostIt\r\n".
"Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: $contentlength\r\n\r\n".
"$reqbody\r\n";
$socket = fsockopen($host, 80, $errno, $errstr);
if (!$socket) {
$result["errno"] = $errno;
$result["errstr"] = $errstr;
return $result;
}
fputs($socket, $reqheader);
while (!feof($socket)) {
$result[] = fgets($socket, 4096);
}
fclose($socket);
return $result;
}
?>
28-Jun-2007 07:24
If you want to send more than one custom header, just make header an array:
<?php
$default_opts = array(
'http' => array(
'user_agent' => 'Foobar',
'header' => array(
'X-Foo: Bar',
'X-Bar: Baz'
)
)
);
stream_context_get_default($default_opts);
readfile('http://www.xhaus.com/headers');
?>
17-Nov-2006 05:18
As it says on this page:
"The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3.0, the headers are available using stream_get_meta_data()."
This one sentence is the only documentation I have found on the mysterious $http_response_header variable, and I'm afraid it's misleading. It implies that from 4.3.0 onward, stream_get_meta_data() ought to be used in favor of $http_response_header.
Don't be fooled! stream_get_meta_data() requires a stream reference, which makes it ONLY useful with fopen() and related functions. However, $http_response_header can be used to get the headers from the much simpler file_get_contents() and related functions, which makes it still very useful in 5.x.
Also note that even when file_get_contents() and friends fail due to a 4xx or 5xx error and return false, the headers are still available in $http_response_header.
