Skip to content

Commit dedfcbc

Browse files
authored
add CORS 1.0
1 parent cc579e3 commit dedfcbc

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

App/Models/CORS.php

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
3+
namespace Monster\App\Models;
4+
5+
class CORS
6+
{
7+
// Initialize private properties to store CORS settings
8+
private $allowedOrigins = array();
9+
private $allowedMethods = array();
10+
private $allowedHeaders = array();
11+
private $exposedHeaders = array();
12+
private $maxAge = 0;
13+
private $allowCredentials = false;
14+
15+
// Constructor to set CORS settings when creating a new instance of the class
16+
public function __construct($allowedOrigins = array(), $allowedMethods = array(), $allowedHeaders = array(), $exposedHeaders = array(), $maxAge = 0, $allowCredentials = false)
17+
{
18+
// Set the allowed origins, methods, headers, exposed headers, max age, and allow credentials properties
19+
$this->allowedOrigins = $allowedOrigins;
20+
$this->allowedMethods = $allowedMethods;
21+
$this->allowedHeaders = $allowedHeaders;
22+
$this->exposedHeaders = $exposedHeaders;
23+
$this->maxAge = $maxAge;
24+
$this->allowCredentials = $allowCredentials;
25+
}
26+
27+
// Method to set CORS headers based on the properties set in the constructor
28+
public function setHeaders()
29+
{
30+
// Check if the allowed origins include all origins by checking if '*' is in the array
31+
if (in_array('*', $this->allowedOrigins)) {
32+
// Allow all origins with a wildcard
33+
header('Access-Control-Allow-Origin: *');
34+
} else {
35+
// Check if the origin of the request is in the allowed origins array
36+
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
37+
if (in_array($origin, $this->allowedOrigins)) {
38+
// Set the allowed origin to the origin of the request
39+
header("Access-Control-Allow-Origin: $origin");
40+
}
41+
}
42+
// Check if credentials are allowed and set the allow credentials header if true
43+
if ($this->allowCredentials) {
44+
header('Access-Control-Allow-Credentials: true');
45+
}
46+
// Set the exposed headers header if there are any exposed headers
47+
if (!empty($this->exposedHeaders)) {
48+
header('Access-Control-Expose-Headers: ' . implode(', ', $this->exposedHeaders));
49+
}
50+
// Set the max age header if the max age is greater than 0
51+
if ($this->maxAge > 0) {
52+
header("Access-Control-Max-Age: $this->maxAge");
53+
}
54+
// Set the allowed methods header if there are any allowed methods
55+
if (!empty($this->allowedMethods)) {
56+
header('Access-Control-Allow-Methods: ' . implode(', ', $this->allowedMethods));
57+
}
58+
// Set the allowed headers header if there are any allowed headers
59+
if (!empty($this->allowedHeaders)) {
60+
header('Access-Control-Allow-Headers: ' . implode(', ', $this->allowedHeaders));
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)