CakeFest 2024: The Official CakePHP Conference

Exemplo básico de cURL

Uma vez que o PHP tenha sido compilado com suporte a cURL, pode-se começar a usar as funções cURL. A ideia por trás das funções cURL é inicializar uma sessão cURL usando curl_init(), o que permite configurar as opções para a transferência através de curl_setopt(), e depois executar a sessão com curl_exec(), finalizando a sessão com curl_close(). Aqui está um exemplo que usa as funções cURL para receber o conteúdo da página inicial de exemplo.com.br em um arquivo:

Exemplo #1 Usando o módulo cURL do PHP para receber a página exemplo.com.br

<?php

$ch
= curl_init("http://www.exemplo.com.br/");
$fp = fopen("pagina_exemplo.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
if(
curl_error($ch)) {
fwrite($fp, curl_error($ch));
}
curl_close($ch);
fclose($fp);
?>

add a note

User Contributed Notes 1 note

up
45
Roberto Braga
8 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