php curl post请求中携带header参数
php curl post请求中携带header参数
$url = 'http://localhost/test.php';
$ch = curl_init ();
// curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
'X-ptype: like me'
) );
curl_setopt ( $ch, CURLOPT_POST, count ( $post_data ) );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, http_build_query ( $post_data ) );
ob_start ();
curl_exec ( $ch );
$result = ob_get_contents ();
ob_end_clean ();
curl_close ( $ch );
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
//或者
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: "; // browsers keep this blank.
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
php://input
php://input是个可以访问请求原始数据的只读流,但是对于enctype=”multipart/form-data”表单数据也是不可用的(同$HTTP_RAW_POST_DATA)。
如果PHP使用php://input来处理post数据,请求报文中不需要添加Content-Type头
<?php
public function request_post(){
echo file_get_contents('php://input');
}
?>
PHP 处理Request header
在PHP里,想要得到所有的HTTP请求报头,可以使用getallheaders方法,不过此方法并不是在任何环境下都存在,比如说,你使用fastcgi方式运行php的话,就没有这个方法,所以说我们还需要考虑别的方法,幸运的是$_SERVER里有我们想要的东西,它里面键名以HTTP_开头的就是HTTP请求头:
$headers = array();
foreach ($_SERVER as $key => $value) {
if ('HTTP_' == substr($key, 0, 5)) {
$headers[str_replace('_', '-', substr($key, 5))] = $value;
echo "$key: $value\n";
}
}
php发送post请求的三种方法,分别使用curl、file_get_content、fsocket来实现post提交数据
/** * 发送post请求
* @param string $url 请求地址
* @param array $post_data post键值对数据
* @return string
* */
function send_post($url, $post_data) {
$postdata = http_build_query($post_data);
'http' => array( 'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 15 * 60 // 超时时间(单位:s)
));
$context = stream_context_create($options);
return $result;
}
//使用方法
$post_data = array('password' =>'handan');
send_post('http://www.jb51.net', $post_data);
<?php
/**
* Socket版本
* $post_string = "app=socket&version=beta";
* request_by_socket('chajia8.com', '/restServer.php', $post_string);
* /
function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30)
{
$socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout);
if (!$socket) die("$errstr($errno)");
fwrite($socket, "POST $remote_path HTTP/1.0");
fwrite($socket, "HOST: $remote_server");
fwrite($socket, "Content-length: " . (strlen($post_string) + 8) . "");
fwrite($socket, "");
fwrite($socket, "");
while ($str = trim(fgets($socket, 4096)))
{
$header .= $str;
}
$data = "";
while (!feof($socket))
{
$data .= fgets($socket, 4096);
}
return $data;
}
?>