您的位置:首页 > 编程语言 > PHP开发

php模拟POST请求的两种方法

2011-10-13 11:54 381 查看
通过fsockopen函数

<?php

//模拟发送POST请求

$url = "http://localhost/Post/server.php";//要请求的服务器地址

//要请求的内容

$post_data['user'] = "root";

$post_data['password'] = "1988725";

//转换请求内容

foreach($post_data as $key => $value)

{

$requestArray[] = $key.'='.urlencode($value);

}

$requestString = implode("&",$requestArray);

//url

$url_info = parse_url($url);

if(!isset($url_info['port']))

{

$url_info['port'] = 80;

//模拟http请求头

$request .= "POST ".$url_info['path']." HTTP/1.1\n";

$request .= "Host: ".$url_info['host']."\n";

$request .= "Content-type: application/x-www-form-urlencoded\n";

$request .= "Content-length: ".strlen($requestString)."\n";

$request .= "Connection: close\n";

$request .= "\n";

$request .= $requestString."\n";

}

$fp = fsockopen($url_info["host"], $url_info["port"]);

fputs($fp, $request);//把HTTP头发送出去

$inheader = 1;

while(!feof($fp))

{

//$result 是提交后返回的数据

$result .= fgets($fp, 1024);

}

echo $result;

fclose($fp);

通过 crul

<?php

//要请求的内容

$post_data['user'] = "root";

//$post_data['password'] = "1988725";

$post_data['file'] = '@C:\Documents and Settings\chenzhi\My Documents\My Pictures\1286606098_38.jpg';

///$post_data['file'] = '@'.$_FILES['image']['tmp_name'];

$ch = curl_init();

$curl_url = "http://172.16.27.51/server.php";

curl_setopt($ch,CURLOPT_URL,$curl_url);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不直接输出,返回到变量

//$curl_result = curl_exec($ch);

//echo $curl_result;

curl_exec($ch);

注意,通过curl传送图片时,一定要记住要加@号,且不能用双引号,只能用单引号
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: