php设置http请求头信息和响应头信息

php设置http请求头信息和响应头信息

设置请求服务器的头信息可以用fsockopen,curl组件,header函数只能用来设置客户端响应的头信息,不能设置服务器的头信息.

例子;

 一.header函数的用法

    header('WWW-Authenticate: Negotiate');

    header('User-Agent:Mozilla/5.0);

多个直接要写多个header,不可以连接在一起

二.fsockopen函数的用法

1.php

<?php
$fp = fsockopen("test.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET /2.php HTTP/1.1\r\n";
    $out .= "Host: test.com\r\n";

    $out .= "name:longqiqi\r\n";
    $out .= "Connection: Close\r\n\r\n";

    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

2.php

print_r(getallheaders());

会返回自己设置请求的头信息

三.curl组件的使用

1.php

<?php

function FormatHeader($url, $myIp = null,$xml = null)

{

 // 解悉url

 $temp = parse_url($url);

 $query = isset($temp['query']) ? $temp['query'] : '';

 $path = isset($temp['path']) ? $temp['path'] : '/';

 

 $header = array (

 "POST {$path}?{$query} HTTP/1.1",

 "Host: {$temp['host']}",

 "Content-Type: text/xml; charset=utf-8",

 'Accept: */*',

 "Referer: http://{$temp['host']}/",

 'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1)',

 "X-Forwarded-For: {$myIp}",

 "Content-length: 380",

 "Connection: Close"

 );

 

 return $header;

}

 

$interface = 'http://test.com/2.php';

$header = FormatHeader($interface,'10.1.11.1');

 

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $interface);

curl_setopt($ch, CURLOPT_HTTPHEADER, $header);  //设置头信息的地方

curl_setopt($ch, CURLOPT_HEADER, 0);    //不取得返回头信息

curl_setopt($ch, CURLOPT_TIMEOUT, 5);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

 

var_dump($result);

?>

2.php

print_r(getallheaders());

会返回自己设置请求的头信息

#Php

转载于:https://www.cnblogs.com/yisuo/p/6784099.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值