php – Curl Posts Tracking

Question:

I'm trying to POST with curl to verify my deliveries. But nothing is returning. Can someone help me?

<?php    
$post = array('Objetos' => 'PN752805878BR');

// iniciar CURL
$ch = curl_init();
// informar URL e outras funções ao CURL
curl_setopt($ch, CURLOPT_URL, 'http://www2.correios.com.br/sistemas/rastreamento');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($post));
// Acessar a URL e retornar a saída
$output = curl_exec($ch);
// liberar
curl_close($ch);
// Imprimir a saída
echo $output;    
?>

Answer:

This curl was made not to work, actually the problems:

  1. Your call is to the wrong page, /sistemas/rastreamento , when accessing the page through the browser and "trace" some order, you make a request for another page, /sistemas/rastreamento/resultado.cfm? .

    This second page is the correct one, at least it's the one that was made to receive the form's data.

  2. The website requires you to submit a Referer and it would be ideal, although not necessary , to define a User-Agent.


That would be enough:

$post = ['objetos' => 'PN752805878BR', 'btnPesq' => 'Buscar'];

$ch = curl_init('http://www2.correios.com.br/sistemas/rastreamento/resultado.cfm?');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, 'http://www2.correios.com.br/sistemas/rastreamento/');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

echo $output = curl_exec($ch);

If you don't want to use CURLOPT_USERAGENT and CURLOPT_REFERER you can directly use CURLOPT_HTTPHEADER , which I personally prefer. Adding other fixes such as limiting protocols and supporting data compression could use:

$post = ['objetos' => 'PN752805878BR', 'btnPesq' => 'Buscar'];

$ch = curl_init('http://www2.correios.com.br/sistemas/rastreamento/resultado.cfm?');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Referer: http://www2.correios.com.br/sistemas/rastreamento/',
        'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
    ],
    CURLOPT_POSTFIELDS => $post,
    CURLOPT_ENCODING => '',
    CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS
]);

echo $output = curl_exec($ch);

After testing remove the echo to not show the result on the page, and use $output as you wish. Either way this is not completely secure, the website you are connecting to does not support HTTPS, which exposes you to several problems.

Scroll to Top