cURL 예시

만약 cURL 을 사용할 수 있도록 PHP 가 구성되어 있다면 cURL 함수를 사용할 수 있습니다. cURL 함수는 curl_init() 함수를 이용하여 cURL 핸들을 초기화 한 후에, curl_setopt() 함수를 이용하여 전송 정보에 대한 설정을 하고, curl_exec() 함수로 실행할 수 있습니다. 실행한 후에는 curl_close() 를 사용하여 cURL 핸들을 닫을 수 있습니다. 여기에 example.com 사이트의 데이터를 파일로 저장하는 cURL 함수에 대한 예시가 있습니다 :

Example #1 PHP cURL 모듈로 example.com 페이지를 받아와서 저장하기

<?php

$ch 
curl_init("http://www.example.com/");
$fp fopen("example_homepage.txt""w");

curl_setopt($chCURLOPT_FILE$fp);
curl_setopt($chCURLOPT_HEADER0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

add a note add a note

User Contributed Notes 1 note

up
53
Roberto Braga
9 years ago
It is important to notice that when using curl to post form data and you use an array for CURLOPT_POSTFIELDS option, the post will be in multipart format

<?php
$params
=['name'=>'John', 'surname'=>'Doe', 'age'=>36)
$defaults = array(
CURLOPT_URL => 'http://myremoteservice/',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
?>
This produce the following post header:

--------------------------fd1c4191862e3566
Content-Disposition: form-data; name="name"

Jhon
--------------------------fd1c4191862e3566
Content-Disposition: form-data; name="surnname"

Doe
--------------------------fd1c4191862e3566
Content-Disposition: form-data; name="age"

36
--------------------------fd1c4191862e3566--

Setting CURLOPT_POSTFIELDS as follow produce a standard post header

CURLOPT_POSTFIELDS => http_build_query($params),

Which is:
name=John&surname=Doe&age=36

This caused me 2 days of debug while interacting with a java service which was sensible to this difference, while the equivalent one in php got both format without problem.
To Top