background image

使用 PHP 来发送 HTTP 请求

header 函数可以用来发送 HTTP 请求和响应的表头

函数原型

void header(string string [, bool replace [, int http_response_code]])

string 是 HTTP 表头的字符串

如果 replace 为 TRUE,表示要用目前的表头替换之前相似的表头;如果 replace 为 FALSE,表示要使
用多个相似的表头,默认值为 TRUE

http_response_code 用来强制 HTTP 响应码使用 http_response_code 的值

实例:

1. <?php 
2.

// 打开 Internet socket 连接

 

3.

$fp

 = fsockopen(www.00aq.com, 80); 

4.

// 写入 HTTP 请求表头

 

5. fputs(

$fp

"GET / HTTP/1.1\r\n"

); 

6. fputs(

$fp

"Host: www.00aq.com\r\n\r\n"

); 

7.

// HTTP 响应的字符串

 

8.

$http_response

 = 

""

9.

while

 (!feof(

$fp

)) 

10. { 
11.

// 读取 256 位的 HTTP 响应字符串

 

12.

$http_response

 .= fgets(

$fp

, ); 

13. } 
14.

// 关闭 Internet socket 连接

 

15. fclose(

$fp

); 

16.

// 显示 HTTP 响应信息

 

17. echo nl2br(htmlentities(

$http_response

)); 

18. ?>