I have created a mail service on php, this service send letter to some user. Here is a code:
<?php
require 'vendor/autoload.php';
header('Content-type : application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With, content-type');
$response = array(
'text' => '');
if(!empty($_POST)){
$json = json_decode($_POST["req"]);
$key = $json->key;
$sub = $json->subject;
$toemail = $json->emailTo;
$FromEmail = $json->emailFrom;
$html = $json ->html;
$sendgrid = new SendGrid($key);
$email = new SendGrid\Email();
$email->addTo($toemail)
->setFrom($FromEmail)
->setSubject($sub)
->setHtml($html);
$sendgrid->send($email);
$response['text'] = 'Email was sent from '.$FromEmail.' to'. $toemail.'. Success.';
}else{
$response['text'] = 'Sorry! $_POST is undefind';
}
echo json_encode($response);
?>
I need to create a cross domain request to this service using Angular.js.
Here is my code:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
app.controller("emailCtrl", function ($scope, $http) {
var dataForAdminNewsletter = angular.toJson({
key: "********************************************",
subject: "New Email",
emailTo: "mail1#mail.com",
emailFrom: "mail1#mail.com",
html: 'You have a new subscriber' + $scope.emailField
});
$scope.sendPost = function () {
$http({
url: 'http://my.azurewebsites.net/mail.php',
method: "POST",
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: {
"req": dataForAdminNewsletter
}
});
}
});
As the result I have got the next error: XMLHttpRequest cannot load my.azurewebsites.net/mail.php. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:11708' is therefore not allowed access.
I can not change the code on the server side. Can somebody help me to resolve this issue with Angular?
Thank you.
I am using this lines in apache virtual host conf,
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>
<IfModule mod_headers.c>
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"
</IfModule>
And it works as charm, may be this help.
simply put- You can't.
CORS should be enabled in the server for the angular service or as a matter of fact any external service to communicate with it.
Ref: https://gist.github.com/mlynch/be92735ce4c547bd45f6
Use fiddler or chromium devTools to check the request and response.
The response from the server should have the CORS Header.
changing the angular service request will not do any good
additionally You can check this link - https://forum.ionicframework.com/t/http-no-access-control-allow-origin-problem-on-post/5625/6
Related
I'm building an API to activate and validate active installations of my PHP Scripts,
but I get the "Access to XMLHttpRequest at 'http://api.domain.te/requests/verify' from origin 'http://domain.te' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource" error on console.
Here is my jQuery code:
function verify() {
$.post(url+"requests/verify", {
domain: domain
}, function(data) {
if (data.success === true) {
return true;
}
});
return false;
}
I have read through similar questions and tried all the suggestions, but none seems to be working.
On my PHP code I have:
public function verify()
{
$data['success'] = false;
$data['status'] = 'error';
$data['message'] = 'An error occurred';
if ($this->actives_m->check($this->request->getPost("domain")??""))
{
$data['success'] = true;
$data['status'] = 'success';
$data['message'] = 'Product is Active!';
}
else
{
$data['message'] = 'Product is Inactive!';
}
$this->response->setHeader('Access-Control-Allow-Origin', '*');
$this->response->setHeader('Access-Control-Allow-Methods', 'GET, POST');
return $this->response->setJSON($data);
}
I have also tried setting the headers at the beginning of the script after <?php but still did not work.
I also tried the built in PHP header() function like so:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
I have even modified my JS to look like:
function verify() {
$.ajax({
url: url+"requests/verify",
type: "POST",
dataType: "JSON",
data: {domain: domain},
crossDomain: true,
success: function(data) {
if (data.success === true) {
return true;
}
}
});
return false;
}
So far nothing seems to be working, Where should I go from here?
UPDATE:
I realize that if I use Pure Javascript like:
const xhr = new XMLHttpRequest();
xhr.open('GET', url+"requests/verify");
xhr.onreadystatechange = function(data) {
if (data.success === true) {
return true;
}
}
xhr.send();
It works as expected, but I have to use jQuery to keep my code uniform, and for future reference.
Whenever, there is a cross-origin issue, there are two routes that are hit. Lets say in your example, you have GET request to "http://api.domain.te/requests/verify", So before hitting your server with GET request it will hit same url with OPTIONS request. This verifies whether your server allows the API for the Cross Origin Request.
So In CI4 routes you have to define same URL or include a wild card to enable your cross origin request.
Here, the following example is for wild card request.
$routes->options('(:any)', 'Controller/options');
Here this route matches any routes with OPTIONS method and a single method called Options is there to handle it.
This options method can be defined as follows :
public function options($any)
{
return $this->response->setHeader('Access-Control-Allow-Origin', '*') //for allow any domain, insecure
->setHeader('Access-Control-Allow-Headers', '*') //for allow any headers, insecure
->setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE') //method allowed
->setStatusCode(200); //status code
}
What this method essentially does is lets the browser know that request are allowed for Cross-Origin, with status Methods such as GET, POST, PUT and DELETE.
After browser hits this request, it will be directed to your request which should also have cross origin enabled as follow:
$this->response->setContentType('application/json')->setJSON($response)->send()->setHeader('Access-Control-Allow-Origin', '*');
Reference : https://carminemilieni.it/2019/09/19/resolve-cors-and-corb-in-codeigniter-4/
As you already do, CORS must be approached from the receiving server side, so I put headers from .htaccess in Apache sites (check how to do it if you use different server):
Header set Access-Control-Allow-Origin "*"
(in your case, it should be a * if can be multiple unknown domains)
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
(or the method ones if you want too)
Info and options on that header:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
You can check what headers are you sending out by using curl, do they appear?
curl -I http://api.domain.te/requests/verify
I am trying to upload images from my Angular 8+ frontend to my php backend and sending text data works without a problem, but wanting to send image files to a folder in my wamp directory, no cigar unfortunately...
It worked earlier, but this morning it decided it did not want to work anymore. I tried adding to the CORS headers, but nothing seems wrong there.
html:
<input type="button" value="Test" (click)='Advertise($event.target.files)'>
component:
ToUpload()
{
let images = this.carImages.nativeElement;
let j=10;
for(let i of images.files)
{
console.log(i);
if(i.type=='image/jpeg')
{
let frmData = new FormData();
frmData.append('file',i,(j+'.jpg').toString());
this.uploadService.UploadImages(frmData).subscribe(val=>
{
})
}
if(i.type=='image/png')
{
let frmData = new FormData();
frmData.append('file',i,(j+'.png').toString());
this.uploadService.UploadImages(frmData).subscribe(val=>
{
})
}
j++;
}
}
Advertise(files:FileList)
{
this.ToUpload();
}
service:
UploadImages(image:FormData):Observable<any>
{
return this.httpClient.post(this.apiURL+"/api/BLL/imageUpload.php?action=upload",image) as Observable<any>;
}
CORS_Headers.php
<?php
// Default Header
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization,Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("MIME-Version: 1.0");
header("Content-type:text/html;charset=UTF-8");
// Response type header
header('Content-Type: application/json');
?>
imageUpload.php
<?php
require_once '../BLL/CORS_Headers.php';
//require '../DAL/DBHandler.php';
//use DAL\DBHandler;
$action=$_GET['action'];
if($action=='upload')
{
$tempPath = $_FILES['file']['tmp_name'];
// Get File Name
$actualName = $_FILES['file']['name'];
// New path
$actualPath = '../Images/' . $actualName;
//$tempPath = compressImage($tempPath,$actualPath,60);
// Move File into new path
move_uploaded_file($tempPath, $actualPath)
// Get real path of moved file here
$realPath = realpath(__DIR__ . '/' . $actualPath);
// Delete the file
echo "Uploaded";
}
Expected result: Just do the upload
Actual result: Access to XMLHttpRequest at 'http://localhost:3000/api/BLL/imageUpload.php?action=upload' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
and
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/api/BLL/imageUpload.php?action=upload", ok: false, …}
try this
Add below Code in .htaccess file PHP(Server) side
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "X-Requested-With, content-type"
</IfModule>
Angular Code
page.html
<input type="file" (change)="fileUpload($event)" />
npm install
"rxjs": "~6.5.1", //npm i rxjs#6.5.1 --save
"rxjs-compat": "^6.5.2" // npm i rxjs-compat#6.5.2 --save
page.ts
import 'rxjs/add/observable/from';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/concatMap';
fileUpload(event){
let formData = new FormData();
formData.append('file', event.target.files[0]);
this.ImageUpload(formData).subscribe(val => {
//enter custom code
})
}
ImageUpload(formData):Observable<any>{
var token = localStorage.getItem('keyToken');
const myHeaders = new HttpHeaders({ 'Authorization': token });
return this.http
.post(URL, formData,{headers:myHeaders})
.concatMap(data=>{
return Observable.of(data);
})
}
I'm currently working on a PHP REST API for a uni project, which uses JSON web tokens passed from mobile web applications using PhoneGap, or my desktop during development.
When sending the token to my server page "friends/read.php" using ajax, the server was picking up the Authorization header correctly with
$headers = getallheaders();
$authHeader = $headers['Authorization'];
but stopped doing so after several successful runs. After that point, the header is no longer being picked up.
My request code is as follows:
$.ajax({
url: "http://localhost/chordstruck/api/friends/read.php",
type: "GET",
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('jwt'));
},
datatype: "json",
success: function (response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
Oddly enough, when killing the PHP script prematurely with die("test") and then removing die() again, the server will then start picking up the Authorization header for several more requests.
Read.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token');
$config = require_once '../config/core.php';
require_once '../config/jwt_helper.php';
// get database connection
include_once '../config/database.php';
// instantiate profile object
include_once '../objects/profile.php';
$headers = getallheaders();
$authHeader = $headers['Authorization'];
$token;
if ($authHeader) {
list($jwt) = sscanf((string)$authHeader, 'Bearer %s');
if ($jwt) {
try {
$key = $config['jwt_key'];
$token = JWT::decode($jwt, $key, array('HS512'));
} catch (Exception $e) {
header('HTTP/1.0 401 Unauthorized');
exit();
}
} else {
header('HTTP/1.0 400 Bad Request');
exit();
}
} else {
header('HTTP/1.0 400 No Header Found');
exit();
}
echo "success";
?>
I have been encountering a CORS issue while developing this project, which I've countered with the above headers along with the following in my .htaccess file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
Could this potentially be related? Any help/ideas would be greatly appreciated!
The problem appears to have been indeed related to CORS and after trying a multitude of approaches, the following solution is now working.
Replacing my headers in read.php with:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
// may also be using PUT, PATCH, HEAD etc
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);
}
Credit goes to slashingweapon who used it to answer CORS with php headers
I have created an app for the Registration Form using [Ionic + PHP] and I face the following issue.
CORS Add-on: Activated - It works Fine when I use it in the http://localhost:8100/ionic-lab
CORS Add-on: Deactivated - It does not works Fine when I use it in the http://localhost:8100/ionic-lab and the below mentioned error occurs.
Below I will explain the codes in my Files.
remote-service.ts
constructor(public http: Http) {
this.headers = new Headers()
this.headers.append('Content-Type', 'application/json')
this.headers.append('Content-Type', 'application/x-www-form-urlencoded')
this.headers.append('Access-Control-Allow-Origin', 'http://localhost:8100')
this.headers.append('Access-Control-Allow-Credentials', 'true')
this.headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD')
this.headers.append('Access-Control-Allow-Origin', '*')
this.headers.append('Accept', 'application/json')
this.headers.append('Accept', 'application/x-www-form-urlencoded')
console.log('Hello RemoteServiceProvider Provider');
}
getAllUsers() {
let options = new RequestOptions({ headers: this.headers })
return this.http.get('http://haitutorial.com/HybridApp/listAllUsers.php', options)
.map(res => res.json());
}
getAllUsers() - This function will fetch all the users Registered from the specific URL.
database.php
<?php
include('database.php');
header('Access-Control-Allow-Origin' , '*');
header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
header('Accept','application/json');
header('content-type','application/json');
$query = "SELECT * FROM `users` WHERE `status`='1' AND `delete_status`='0' ORDER BY `user_id` DESC";
$result = mysqli_query($con,$query);
$count = mysqli_num_rows($result);
$resultant_array = array();
if($count>0)
{
while($informations = mysqli_fetch_assoc($result))
{
$resultant_array[] = $informations;
}
print_r(json_encode($resultant_array));
}
else
{
$resultant_array[] = ["success"=> 200, "message"=> "No Data Found", "status_code"=>1 ];
echo $output = json_encode($resultant_array);
}
?>
The Above URL mentioned in the getAllUsers() works in the Browser but when placed inside the Ionic App it shows the below Error.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://haitutorial.com/HybridApp/listAllUsers.php. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
The above Issue is solved when I enable the CORS add-on in the Browser. But when I Disable the CORS add-on in the Browser it shows the Error.
Like wise the Same Error prevails in the Insert Page Also. When I Insert the Data from the APP it redirects to the List Page and the Data are not displayed telling the above said Error.
I have added header() in the PHP File also. But I am unable to trace out the Error. I am in need to Fix this Error without the use of Add-on like stuffs in the browser and needs to run successfully in APP too.
You need to set header at server end not ionic side.
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
I am trying to allow access to every subdomain on my site in order to allow cross subdomain AJAX calls. Is there a way to specify all subdomains of a site like *.example.com or alternatively, why does the following not work when I have more than one domain listed:
header('Access-Control-Allow-Origin: http://api.example.com http://www.example.com');
I have read through the following question which appears to be similar, if not the same as this one, other than the fact that I want access to subdomains and this one refers to general domains.
Access-Control-Allow-Origin Multiple Origin Domains?
If the above question is the solution to this problem, then how am I able to retrieve the origin from the header. It appears that $_SERVER['HTTP_ORIGIN'] is very unreliable and not even cross browser. I need to be able to see the origin in any browser that may show an error when trying to send an AJAX call using javascript.
The solution to this issue is to use the $_SERVER['HTTP_ORIGIN'] variable to determine whether the request has come from an allowed domain, and then conditionally set the Access-Control-Allow-Origin like so:
$allowed_domains = [/* Array of allowed domains*/];
if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}
Here's how I did it.
The Origin header is specified by the browser and will contain the domain that requested the script on the other domain:
Origin: http://www.websiteA.com
Therefore you can "whitelist" multiple domains in your server-side script:
$allowedOrigins = [
"http://www.websiteA.com",
"https://www.websiteB.com"
// ... etc
];
What you can then do is check if the $_SERVER["HTTP_ORIGIN"] global contains a domain within that whitelist:
if (in_array($_SERVER["HTTP_ORIGIN"], $allowedOrigins)) {
And set the Access-Control-Allow-Origin response header to whatever Origin header value was:
header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);
Full script:
$allowedOrigins = [
"http://www.websiteA.com",
"https://www.websiteB.com"
// ... etc
];
if (in_array($_SERVER["HTTP_ORIGIN"], $allowedOrigins)) {
header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);
}
While the answer works, it does defeat the purpose of the whole thing, since it allows requests from any host.
I use something like:
if(isset($_SERVER['HTTP_ORIGIN'])) {
$origin = $_SERVER['HTTP_ORIGIN'];
if($origin == 'https://sub1.my-website.com' OR $origin == 'https://sub2.my-website.com') {
header("Access-Control-Allow-Origin: $origin");
}
}
If you want wildcard domain, i think this is more efficient
if(isset($_SERVER['HTTP_ORIGIN']) && preg_match('!^http(s)?://([a-z0-9\-]+\.)?example\.com$!is', $_SERVER['HTTP_ORIGIN']))
{
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
}
I tried using this approach to achieve constraint on a specific domain basis:
$allowed_origin = '';
$parts = explode('.', parse_url($_SERVER['HTTP_HOST'])['host']);
if(end($parts).".".prev($parts) === "com.domain") {
$allowed_origin = $_SERVER['HTTP_ORIGIN'];
header('Acesss-Control-Allow-Origin: '. $allowed_origin);
}
I hope it works.
//Function to be called first in php file.
function CORS_HEADERS_HANDLER(){
if (isset($_SERVER['HTTP_ORIGIN'])){
switch($_SERVER['HTTP_ORIGIN']){
//Handle an IP address and Port
case 'http://1.2.3.4:4200':
header('Access-Control-Allow-Origin: http://1.2.3.4:4200');
break;
//Handle an Website Domain (using https)
case 'https://www.someSite.com':
header('Access-Control-Allow-Origin: https://www.someSite.com');
break;
//Handle an Website Domain (using http)
case 'http://www.someSite.com':
header('Access-Control-Allow-Origin: http://www.someSite.com');
break;
//Catch if someone's site is actually the reject being cheeky
case 'https://not.you':
header('Access-Control-Allow-Origin: https://nice.try');
break;
//Handle a rejection passing something that is not the request origin.
default:
header('Access-Control-Allow-Origin: https://not.you');
break;
}
}else{
header('Access-Control-Allow-Origin: https://not.you');
}
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json; charset=utf-8');
header("Cache-Control: public,max-age=3600");
//if its an options request you don't need to proceed past CORS request.
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
die();
}
}
This was my challenge and solution:
1 - Backend PHP on api.example.com.
2 - Multiple JS front ends such as one.example.com, two.example.com etc.
3 - Cookies needed to be passed both ways.
4 - AJAX call from multiple front-ends to PHP backend on api.example.com
5 - In PHP, I do not prefer to use $_SERVER["HTTP_ORIGIN"], not always reliable/safe in my opinion (I had some browsers where HTTP-ORIGIN was always empty).
The normal way to do this in PHP with single front end domain is starting PHP code with:
header('Access-Control-Allow-Origin: https://one.example.com');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header('Access-Control-Allow-Credentials: true');
And in JS on one.example.com domain:
jQuery.ajax({
url: myURL,
type: "POST",
xhrFields: {withCredentials: true},
dataType: "text",
contentType: "text/xml; charset=\"utf-8\"",
cache: false,
headers: "",
data: myCallJSONStr,
success: function(myResponse) {.....}
However, this is not workable as I am using multiple subdomains to call my API domain.
And this solution will NOT work as I want to pass on cookies:
header('Access-Control-Allow-Origin: *');
It conflicts with the pass on cookie setting on the JS site:
xhrFields: {withCredentials: true}
Here is what I did:
1 - use GET parameter to pass the Subdomain.
2 - Hardcode the Main domain in PHP so only (all) Subdomains are allowed.
This is the JS/JQuery AJAX part of my solution:
function getSubDomain(){
let mySubDomain = "";
let myDomain = window.location.host;
let myArrayParts = myDomain.split(".");
if (myArrayParts.length == 3){
mySubDomain = myArrayParts[0];
}
return mySubDomain;
}
And in the AJAX call:
let mySubDomain = getSubDomain();
if (mySubDomain != ""){
myURL += "?source=" + mySubDomain + "&end"; //use & instead of ? if URL already has GET parameters
}
jQuery.ajax({
url: myURL,
type: "POST",
xhrFields: {withCredentials: true},
dataType: "text",
contentType: "text/xml; charset=\"utf-8\"",
cache: false,
headers: "",
data: myCallJSONStr,
success: function(myResponse) {.....}
Finally, the PHP part:
<?php
$myDomain = "example.com";
$mySubdomain = "";
if (isset($_GET["source"])) {
$mySubdomain = $_GET["source"].".";
}
$myDomainAllowOrigin = "https://".$mySubdomain.$myDomain;
$myAllowOrigin = "Access-Control-Allow-Origin: ".$myDomainAllowOrigin;
//echo $myAllowOrigin;
header($myAllowOrigin);
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header('Access-Control-Allow-Credentials: true');
IMPORTANT, don't forget to set the cookies for all subdomains, in this case the domain for the cookie would be: .example.com (so with a dot in front of the main domain):
<?php
//////////////// GLOBALS /////////////////////////////////
$gCookieDomain = ".example.com";
$gCookieValidForDays = 90;
//////////////// COOKIE FUNTIONS /////////////////////////////////
function setAPCookie($myCookieName, $myCookieValue, $myHttponly){
global $gCookieDomain;
global $gCookieValidForDays;
$myExpires = time()+60*60*24*$gCookieValidForDays;
setcookie($myCookieName, $myCookieValue, $myExpires, "/", $gCookieDomain, true, $myHttponly);
return $myExpires;
}
This solution allows me to call the API on api.example.com from any subdomains on example.com.
NB. for situation where there is only a single calling subdomain, I prefer using .htaccess for setting CORS instead of PHP. Here is an example of .htaccess (linux/apache) for only one.example.com calling api.example.com:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "https://one.example.com"
Header set Access-Control-Allow-Headers "Origin, Content-Type, X-Auth-Token"
Header set Access-Control-Allow-Credentials "true"
</IfModule>
And place this .htaccess in the root of api.example.com.