PHP code example of effectra / cors

1. Go to this page and download the library: Download effectra/cors library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

effectra / cors example snippets


use Effectra\Cors\CorsMiddleware;
use Effectra\Cors\CorsService;
use Psr\Http\Server\MiddlewareInterface;

// Create a CorsService instance with desired configuration
$corsService = new CorsService([
    'allowedOrigins' => ['https://example.com'],
    'allowedMethods' => ['GET', 'POST'],
    'allowedHeaders' => ['Content-Type'],
]);

// Create the CorsMiddleware instance
$corsMiddleware = new CorsMiddleware($corsService, ['/api']);

// Add the middleware to your middleware stack
$middlewareStack = [
    // Other middleware...
    $corsMiddleware,
    // Other middleware...
];

use Effectra\Cors\CorsService;

// Create a CorsService instance with desired configuration
$corsService = new CorsService([
    'allowedOrigins' => ['https://example.com'],
    'allowedMethods' => ['GET', 'POST'],
    'allowedHeaders' => ['Content-Type'],
]);

// Check if a request is a CORS request
$isCorsRequest = $corsService->isCorsRequest($request);

// Check if a request is a preflight request
$isPreflightRequest = $corsService->isPreflightRequest($request);

// Handle a preflight request and add necessary headers to the response
$preflightResponse = $corsService->handlePreflightRequest($request);

// Check if a specific origin is allowed
$isOriginAllowed = $corsService->isOriginAllowed($request);

// Add CORS headers to the actual response
$actualResponse = $corsService->addActualRequestHeaders($response, $request);