1

I am trying to do a cURL POST request defining HTTP Headers with PHP and I am getting CORS problem.

So I have a .php file that is called from a webapp using AJAX. In this .php file I am doing a HTTP POST request to an external API using cURL. It all worked fine until I had to set different HTTP Headers for authentication purposes. When I try to define the HTTP Headers in the cURL request using:

//Set Headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Authorization': 'someAuthorization',
  'x-api-key': 'somekey',
  'Content-Type': 'application/x-www-form-urlencoded'
));

I start getting a CORS problem between the client (webapp) and my own endpoint which wasnt happening before. I tried to define the headers again after executing the cURL request but it didnt work:

//execute post
$result = curl_exec($ch);
if($result === false){
  echo 'Curl error: ' . curl_error($ch);
}else{
//$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//CORS
if (isset($_SERVER['HTTP_ORIGIN'])) {
    //header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header("Access-Control-Allow-Origin: http://localhost:4200");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
}   
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: 
{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    exit(0);
}
echo $result;
};

Any ideas why this is happening? To me it seems that by performing the cURL request I am overriding the headers with cURL so the CORS header configuration is never applied.

Heres all the code in the .php file

<?php

$url = 'someurl';
$fields = ['pax' => '2', 'ownerid' => '1', 'channel' => '3'];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 

//Set Headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization': 'someAuth',
'x-api-key': 'someKey',
'Content-Type': 'application/x-www-form-urlencoded',
));

//DISABLE SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

//execute post
$result = curl_exec($ch);
if($result === false){
  echo 'Curl error: ' . curl_error($ch);
}else{
  //$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  //CORS
  if (isset($_SERVER['HTTP_ORIGIN'])) {
    //header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header("Access-Control-Allow-Origin: http://localhost:4200");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
  }   
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    exit(0);
  }
  echo $result;
};

curl_close($ch);
?>
alexcancode
  • 41
  • 1
  • 1
  • 7

1 Answers1

2

Setting some headers in the curl request dont changes header in your .php script.

UPDATE 1:

There is a parse error in your php script (As you found out by yourself):

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Authorization': 'someAuthorization',
  'x-api-key': 'somekey',
  'Content-Type': 'application/x-www-form-urlencoded'
));

Should be:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Authorization: someAuthorization',
  'x-api-key: somekey',
  'Content-Type: application/x-www-form-urlencoded'
));

The ajax call to this script result in an error 500 response which has default headers and NOT the headers you try to set in your .php script.

Enable error reporting in your local environment to see the problem "earlier".

for example in php.ini:

error_reporting=E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED 
display_errors=On

@see How do I get PHP errors to display?

Steffen Mächtel
  • 981
  • 8
  • 13
  • I already tried that and it didn´t work. Actually thats how it was in the first place, I just moved it down because I thought cURL was the issue. But still get CORS error: "Access to XMLHttpRequest at 'http://localhost/booking/makeTempBooking.php' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control- Allow-Origin' header is present on the requested resource." – alexcancode Dec 24 '18 at 15:16
  • Just for testing, you can try set * to allow all. header("Access-Control-Allow-Origin: *"); You could also check in browser debug console (network) what headers are coming back from you request. (Chrome: https://stackoverflow.com/questions/4423061/view-http-headers-in-google-chrome) – Steffen Mächtel Dec 24 '18 at 15:33
  • Yes, I did that already and its really weird because theres no 'Access-Control-Allow-Origin-*' headers in the Response Headers: `Connection: Keep-Alive Content-Length: 416 Content-Type: text/html; charset=UTF-8 Date: Mon, 24 Dec 2018 18:38:09 GMT Keep-Alive: timeout=5, max=100 Server: Apache/2.4.33 (Win64) OpenSSL/1.1.0g PHP/7.2.4 X-Powered-By: PHP/7.2.4` – alexcancode Dec 24 '18 at 18:40
  • Maybe it gets removed by apache? .htaccess or apache httpd.conf / extras/*.conf? – Steffen Mächtel Dec 24 '18 at 18:46
  • Hmmmm, maybe the return from curl has also headers included (header+body). $result = curl_exec($ch); you use echo $result later. I think there are options to remove headers from response curl_setopt($ch, CURLOPT_HEADER, 0); @see https://stackoverflow.com/questions/5142869/how-to-remove-http-headers-from-curl-response – Steffen Mächtel Dec 24 '18 at 19:00
  • I finally found out what is going on. As I suppoused the error when setting the 'CURLOPT_HTTPHEADER'. I had: //Set Headers curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Authorization': 'someAuth', 'x-api-key': 'someKey', 'Content-Type': 'application/x-www-form-urlencoded', )); And just realized it should be: //Set Headers curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Authorization : someAuth', 'x-api-key : someKey', 'Content-Type : application/x-www-form-urlencoded', )); – alexcancode Dec 24 '18 at 19:16
  • Ah ok, i missed that also :D – Steffen Mächtel Dec 24 '18 at 19:20
  • no comments... haha thank you anyway for the support! – alexcancode Dec 24 '18 at 19:23
  • But one question :o Does your old code with wrong quotes not throw a php fatal error? Its not a valid php syntax: array('Somevalue': 'somevalue'); ? It should output something like Parse error: syntax error, unexpected ':', expecting ')' in – Steffen Mächtel Dec 24 '18 at 19:30
  • Yea It is very weird but it doesn´t :/ – alexcancode Dec 24 '18 at 19:34
  • Maybe you have not enabled error_reporting and display_errors in your configuration? If you work on local environment i prefer enable this in php.ini. // error_reporting=E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED // display_errors=On – Steffen Mächtel Dec 24 '18 at 19:36
  • @totalx i have updated my answer. Maybe its usefull for other people run into CORS problem. – Steffen Mächtel Dec 27 '18 at 12:19