Skip to content

PHP Allow CORS Access

PHP Allow CORS Access

Sometimes, you might need to allow CORS access for various reasons, such as when you have a subdomain like images.domain.com. By default, CORS is denied and must be manually allowed. Here’s how you can do it in a specific php script (note that it only allows CORS access to the specified script, and not the whole site)
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    // should do a check here to match $_SERVER['HTTP_ORIGIN'] to a
    // whitelist of safe domains
    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']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
That’s all.
Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgrammingWeb Server

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *