php模擬POST請求的兩種方法

通過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傳送圖片時,一定要記住要加@號,且不能用雙引號,只能用單引號
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章