DEVEL/PHP
PHP CURL POST 요청하기
codebyai
2023. 3. 15. 17:27
반응형
<?php
// 함수의 이름을 curl_post로 정함
function curl_post($url, $data, $headers = array()) {
// cURL 초기화
$ch = curl_init();
// URL 설정
curl_setopt($ch, CURLOPT_URL, $url);
// HTTP 메소드를 POST로 설정
curl_setopt($ch, CURLOPT_POST, true);
// 보낼 데이터를 URL 인코딩된 문자열로 변환함
$data_string = http_build_query($data);
// 요청 본문으로 설정함
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
// 필요한 경우 HTTP 헤더를 설정함 (예: 콘텐츠 타입)
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
// 요청을 실행함
$result = curl_exec($ch);
// cURL 핸들을 닫음
curl_close($ch);
// 결과를 반환함
return $result;
}
호출예제
<?php
// 함수 호출 예시
// 보낼 데이터 예시
$data = array(
'username' => 'user1',
'password' => 'passuser1',
'gender' => '1'
);
// 헤더 예시
$headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
// 함수 호출 및 결과 출력
echo curl_post('http://www.example.com', $data, $headers);
?>
반응형



