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 3, PHP 4. PHP 4.3.0 이후의 https://
- http://example.com
- http://user:password@example.com
- https://example.com
- 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를 사용하십시오 */
foreach(stream_get_meta_data($fp) as $response) {
/* 어디로 리다이렉트합니까? */
if (substr(strtolower($response), 0, 10) == 'location: ') {
/* 리다이렉트 되는 곳으로 $url을 갱신합니다 */
$url = substr($response, 10);
}
}
?>
스트림은 리소스의 body에 접속할 권한이 있다; 헤더는 $http_response_header 변수에 저장된다. PHP 4.3.0 이후부터, 헤더는 stream_get_meta_data()를 사용하여 이용가능하다.
HTTP 접속은 읽기-전용이다; HTTP 리소스에 데이터를 쓰거나 파일을 복사할수 없다.
Note: HTTPS는 PHP 4.3.0부터 지원되었다. OpenSSL에 대한 지원 옵션으로 컴파일해야 한다.
| 속성 | 지원 |
|---|---|
| allow_url_fopen으로 제한 | Yes |
| 읽기 허용 | Yes |
| 쓰기 허용 | No |
| 추가 허용 | No |
| 동시 읽기/쓰기 허용 | N/A |
| stat() 지원 | No |
| unlink() 지원 | No |
| rename() 지원 | No |
| mkdir() 지원 | No |
| rmdir() 지원 | No |
| 이름 | 사용 | 기본값 |
|---|---|---|
| method | 원격 서버에 의해 지원되는 GET, POST과 다른 모든 HTTP 메소드 | GET |
| header | 요청시 전송되는 추가적인 헤더. 이 옵션 값은 다른 값들(User-agent:, Host:, Authentication:)에 의해 오버라이드될것이다. | |
| user_agent | User-Agent: 헤더에 의해 전송되는 값. 이 값은 user-agent가 header 컨텍스트 옵션에서 설정되지 않을때만 사용될것이다. | php.ini setting: user_agent |
| content | 헤더 다음에 전송되는 추가데이터. 표준적으로 POST나 PUT 요청에서 사용된다. | |
| proxy | 프록시 서버를 지정하는 URI. (예. tcp://proxy.example.com:5100) | |
| request_fulluri | TRUE로 설정하면, 전체 URI를 사용하여 요청을 작성합니다. (예. GET http://www.example.com/path/to/file.html HTTP/1.0) 이는 비표준 요청 형식이지만, 몇몇 프록시 서버는 이를 요구합니다. | FALSE |
Note: 기저(Underlying) 소켓 스트림 컨텍스트 옵션 http:// 스트림에 대한 기저(underlying) 전송에 의해 지원될수 있는 추가 컨텍스트 옵션이고, tcp:// 전송 컨텍스트 옵션으로 참조된다. https:// 스트림에 대해서는 ssl:// 전송 컨텍스트 옵션으로 참조된다.
HTTP 와 HTTPS
26-Jun-2008 04:17
24-Oct-2007 03: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.
29-Jul-2007 04: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 03: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 12: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.
