PHP code example of phputil / cors

1. Go to this page and download the library: Download phputil/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/ */

    

phputil / cors example snippets



use phputil\router\Router;
use function phputil\cors\cors; // Step 1: Declare the namespace usage for the function.
$app = new Router();

$app->use( cors() ); // Step 2: Invoke the function to use it as a middleware.

$app->get( '/', function( $req, $res ) {
    $res->send( 'Hello' );
} );
$app->listen();

function cors( array|CorOptions $options ): callable;

$options = [
    'origin' => 'mydomain.com',
    'methods' => 'GET,POST'
];

$app->use( cors( $options ) );

use phputil\cors\CorsOptions; // Needed

$options = ( new CorsOptions() )
    ->withOrigin( 'mydomain.com' )
    ->withMethods( 'GET,POST' );

$app->use( cors( $options ) );

$options = [
    'origin'            => [ 'https://my-app.com', 'https://authorized-domain.com' ], // Replace with your trusted domains
    'credentials'       => true,
    'allowedHeaders'    => [ 'Accept', 'Authorization', 'Cookie', 'Content-Length', 'Content-Type', 'Host', 'Origin', 'Referer' ],
    'exposeHeaders'     => [ 'Content-Length', 'Content-Type', 'Set-Cookie' ],
    'maxAge'            => 3600 // Cache Preflight requests for 1 hour
];

$app->use( cors( $options ) );