I'm calling a web service that returns a PDF file with Content-Type: application/pdf
I can call the web service from the browser or from Postman, and the resulting file is displayed.
Now I want to call that same service from PHP, and return the response to the client that called the PHP.
I've got this
$url = 'https://localhost:7174/customers/123/pdf';
$expectedMimeType = 'application/pdf';
$token = '****************************************';
$curl = curl_init();
curl_setopt_array(
$curl,
array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '.$token,
'Accept: '.$expectedMimeType
)
)
);
curl_exec($curl);
exit();
I thought that CURLOPT_RETURNTRANSFER would default to false, so PHP would just pass along the response to the caller of the PHP, and that does seem to be what's happening, but it's sending back
Content-Type: text/html; charset=UTF-8
So the PDF file is being displayed in the browser (or in Postman) as a load of binary gobbledegook.
How do I get it to send back the correct Content-Type? Ideally, I would like to pass along the Content-Type from the other web service, so that if the other service ever returns other MIME types, my PHP will just pass it along, but for now, I know it will only ever return PDFs, so I could just hard-code application/pdf if necessary.
With thanks to ADyson for steering me in the right direction. I honestly did not think this would work
<?php
$url = 'https://localhost:7174/customers/123/pdf';
$expectedMimeType = 'application/pdf';
$token = '****************************************';
$curl = curl_init();
curl_setopt_array(
$curl,
array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '.$token,
'Accept: '.$expectedMimeType
)
)
);
$response = curl_exec($curl);
$info = curl_getinfo($curl);
header('Content-Type: '.$info['content_type']);
echo $response;
exit();
but it does. $response comes back as a string, and echo-ing it out with the right content type works perfectly. I thought that because the response was binary data it would lose something when PHP converted it to a string.