混水摸魚

[ PHP ] – CURL POST DEMO FUNCTION 簡易型curl 傳post參數範例

CURL POST DEMO FUNCTION 簡易型curl 傳post參數範例

舊版範例:

$postUrl=$url;//網址
$postBODY = array('name' => 'jeff','age'=>18,'sex'=>1);//post參數
$getBody = my_curl($postUrl,$postBODY);
function my_curl($url,$post){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,  'POST');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    $result = curl_exec($ch);
    curl_close ($ch);
    return $result;
}

新版範例 將 opt 參數陣列化

function curl_post($url, $post_data) {
	$url = $url;
	$data = $post_data;
	$setopts = array(
		CURLOPT_URL		=> $url,
		CURLOPT_RETURNTRANSFER	=> true,
		CURLOPT_HTTPHEADER	=> array(
						"Content-type: multipart/form-data",
						'Content-Length: '.strlen($data),
									),
		CURLOPT_POST			=> true,
		CURLOPT_POSTFIELDS		=> $data,
		CURLOPT_CUSTOMREQUEST	=> "POST"
	);
	$curl = curl_init();
	curl_setopt_array($curl, $setopts);
	$response = curl_exec($curl);
	curl_close($curl);
	return $response;
}

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *