2013年1月10日 星期四

send http post in php

CRUL :

$toURL = "http://example.com/login.aspx";

$post = array(
        "user" => "xxxx",
        "pass" => "xxxx",
);

$ch = curl_init();

$options = array(
        CURLOPT_URL=>$toURL,
        CURLOPT_HEADER=>0,
        CURLOPT_VERBOSE=>0,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_USERAGENT=>"Mozilla/4.0 (compatible;)",
        CURLOPT_POST=>true,
        CURLOPT_POSTFIELDS=>http_build_query($post),
);

curl_setopt_array($ch, $options);

// CURLOPT_RETURNTRANSFER=true 會傳回網頁回應,
// false 時只回傳成功與否
$result = curl_exec($ch);

curl_close($ch);

echo $result;

?>

CRUL-less :
$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);


Reference :
PHP: cURL - Manual
伊沙熊的學習筆記本:【筆記】用PHP+cURL傳送Request (GET,POST或上傳檔案)至另一個網頁 - 樂多日誌
http - How do I send a POST request with PHP? - Stack Overflow

沒有留言:

張貼留言