PHP Allow Multi Cross Domain Request

Server environment

1
2
3
4
5
$ cat /etc/issue
Ubuntu 14.04.5 LTS

$ php -v
PHP 5.6.32-1+ubuntu14.04.1+deb.sury.org+2 (cli)

When using PHP to develop a picture server, the image upload interface will be called by multi projects.
If these projects use completely different domains(non-subdomains), the access interface will fail due to cross-domain restrictions.

If you meet this problem, add the follow php code can help you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
$allowOrigin = [
'http://www.a.com',
'http://www.b.com',
'http://www.c.com',
];

if (in_array($origin, $allowOrigin)) {
header("Access-Control-Allow-Origin: " . $origin);
}

header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //Allow access domain header
header('Access-Control-Allow-Methods:OPTIONS, GET, POST');
header("Content-Type: text/html; charset=utf-8");

Share