LonghornPHP 2026

Exemplos básicos do cURL

Uma vez que o PHP tenha sido compilado com suporte ao 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().

Aqui está um exemplo simples que usa as funções cURL para enviar uma requisição POST:

Exemplo #1 Usando o módulo cURL do PHP para enviar uma requisição POST

<?php
$data = ['foo' => 'bar', 'baz' => 48];
$url = "http://www.example.com/handler.php";

$ch = curl_init($url);

// diz ao CURL para retornar a resposta em vez de enviá-la para stdout
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// define os dados POST, o método correspondente e os cabeçalhos
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

// envia a requisição e obtém a resposta
$response = curl_exec($ch);

if(curl_error($ch)) {
    // trata o erro, ou apenas
    throw new RuntimeException(curl_error($ch));
}

Outro exemplo que usa as funções cURL para enviar uma requisição POST com JSON:

Exemplo #2 Usando o módulo cURL do PHP para enviar uma requisição POST com JSON

<?php
$post_data = ['foo' => 'bar', 'baz' => 48];
$url = "http://www.example.com/api/endpoint";

$ch = curl_init($url);

// diz ao CURL para retornar a resposta em vez de enviá-la para stdout
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// define os dados POST e o método correspondente
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));

// define o cabeçalho necessário
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

// envia a requisição e obtém a resposta
$response = curl_exec($ch);

if(curl_error($ch)) {
    // trata o erro, ou apenas
    throw new RuntimeException(curl_error($ch));
}

Aqui está um outro exemplo que usa as funções cURL para receber o conteúdo da página inicial de exemplo.com.br em um arquivo:

Exemplo #3 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));
}
fclose($fp);

adicionar nota

Notas de Usuários 1 note

up
62
Roberto Braga
11 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