Advertisement
krot

cors php

Feb 12th, 2022
1,320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.40 KB | None | 0 0
  1. /**
  2.  *  An example CORS-compliant method.  It will allow any GET, POST, or OPTIONS requests from any
  3.  *  origin.
  4.  *
  5.  *  In a production environment, you probably want to be more restrictive, but this gives you
  6.  *  the general idea of what is involved.  For the nitty-gritty low-down, read:
  7.  *
  8.  *  - https://developer.mozilla.org/en/HTTP_access_control
  9.  *  - https://fetch.spec.whatwg.org/#http-cors-protocol
  10.  *
  11.  */
  12. function cors() {
  13.    
  14.     // Allow from any origin
  15.     if (isset($_SERVER['HTTP_ORIGIN'])) {
  16.         // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
  17.         // you want to allow, and if so:
  18.         header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
  19.         header('Access-Control-Allow-Credentials: true');
  20.         header('Access-Control-Max-Age: 86400');    // cache for 1 day
  21.     }
  22.    
  23.     // Access-Control headers are received during OPTIONS requests
  24.     if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  25.        
  26.         if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
  27.             // may also be using PUT, PATCH, HEAD etc
  28.             header("Access-Control-Allow-Methods: GET, POST, OPTIONS");        
  29.        
  30.         if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
  31.             header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  32.    
  33.         exit(0);
  34.     }
  35.    
  36.     echo "You have CORS!";
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement