This Curl was made to not work, actually the problems:
Your call is to the wrong page, /sistemas/rastreamento
, when accessing the page by browser and "track" any order, you make a request to another page, /sistemas/rastreamento/resultado.cfm?
.
This second is the correct page, at least it is who was made to receive the form data.
The website requires you to send a Referer
and would be ideal, though not necessary, 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 the CURLOPT_USERAGENT
and the CURLOPT_REFERER
you can directly use the CURLOPT_HTTPHEADER
, which I personally prefer. Adding other fixes such as protocol limitation and support for 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
not to display the result on the page, and use the $output
as you wish. Either way this is not totally safe, the website that is connecting does not support HTTPS, which exposes to various problems.
http://sooho.com.br/2017/03/24/rastreamento-de-pedidos-correios-php-soap/
– Don't Panic