CORS - share files & keep php sessions across subdomains
Building nani-so.re I was faced with a few issues:
I wanted to centralize all static files to a dedicated subdomain static.nani-so.re but I quickly realized that out of the box it is not allowed as Access-Control-Allow-Origin doesn't match, also session are only kept across the same domain
I had to add these lines to .htaccess on the root of static.nani-so.re
```.htaccess
<FilesMatch "\.(ttf|ttc|otf|eot|svg|woff|woff2|php)$">
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://?(.*\.?nani-so.re)$" ORIGIN_SUB_DOMAIN=$0
Header add Access-Control-Allow-Origin %{ORIGIN_SUB_DOMAIN}e env=ORIGIN_SUB_DOMAIN
Header merge Vary "Origin"
</IfModule>
</FilesMatch>
```
this allows any subdomain of nani-so.re to call allowed file types (ttf|ttc|otf|eot|svg|woff|woff2|php) from static.nani-so.re by setting Access-Control-Allow-Origin to the request origin sub domain.
now I request php, fonts, css, ect... files served from static from any nani-so.re subdomain great!
I would like to do the same with cookies and sessions
On the PHP side I added this code
```php
header('Access-Control-Allow-Credentials: true');
session_name("login");
session_set_cookie_params(0, '/', '.nani-so.re');
session_start();
```
by default, CORS does not include cookies on cross-origin requests so the header `Access-Control-Allow-Credentials` set to true fixes that
now I can login from static.nani-so.re and keep session information on all subdomains
the last thing I wanted was to setup an ajax call to refresh the session which I loaded into a php header file that I include on every page
a additional parameters were necessary for the ajax call, I'm using jQuery:
```js
<script>
//PHP SESSION KEEP ALIVE
var refresh_session = function () {
var time = 1200000; // 20 mins - default php session timeout is 24mn
setTimeout(function () {
$.ajax({
url: 'https://static.nani-so.re/keep_alive.php',
cache: false,
xhrFields: {
withCredentials: true
},
complete: function () {
refresh_session();
},
success: function(data) {
console.log(data);
}
});
}, time);
};
refresh_session();
</script>
```
`withCredentials: true` tells jQuery to pass session / cookie parameters to the ajax request, and `cache: false` to make sure we don't cache (without it I had a success response but the session didn't actually refresh...)
now for the php file
```php keep_alive.php
<?php
header('Access-Control-Allow-Credentials: true');
session_name("login");
session_set_cookie_params(0, '/', '.nani-so.re');
session_start();
if(isset($_SESSION['id'])) {
$_SESSION['id'] = $_SESSION['id'];
echo json_encode('session refreshed');
}
else {
echo json_encode('error session not set');
}
?>
```