Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to enable CORS in the PHP CLI server?

Tags:

php

cors

Is it possible to enable CORS in the PHP CLI server (and if so, how)?

Edit: To address comments such as I should just include the header in my scripts, note that I do not have any PHP files/scripts in my code. I am simply using the PHP CLI server as a lightweight local hosting option. Thus ideally the answer will provide a CLI option, or show that there is none.

like image 653
Matthew Herbst Avatar asked Apr 14 '15 00:04

Matthew Herbst


People also ask

How do you enable CORS request in PHP?

To make a GET request with CORS headers, you need to send a 'preflight' OPTIONS request to the server and check if the server can provide the required HTTP headers.

What is CORS PHP?

CORS is a security feature to prevent unauthorized access. It stands for Cross-Origin Resource Sharing. In a browser context, the term “origin” refers to the protocol and hostname parts of a URL. For example, if your full URL is https://example.com/directory/page.html, the origin would be https://example.com.

How do I know if my server is CORS enabled?

You can either send the CORS request to a remote server (to test if CORS is supported), or send the CORS request to a test server (to explore certain features of CORS). Send feedback or browse the source here: https://github.com/monsur/test-cors.org.


2 Answers

Start the server with DocumentRoot in webhook folder with php routings script :

php -S localhost:8888 -t webhook webhook/dev-routings.php

webhook/dev-routings.php :

<?php
// Copyright Monwoo 2017, [email protected]
// Enabling CORS in bultin dev to test locally with multiples servers
// used to replace lack of .htaccess support inside php builting webserver.
// call with :
// php -S localhost:8888 -t webhook webhook/dev-routings.php
$CORS_ORIGIN_ALLOWED = "http://localhost:3000";  // or '*' for all   

function consoleLog($level, $msg) {
    file_put_contents("php://stdout", "[" . $level . "] " . $msg . "\n");
}

function applyCorsHeaders($origin) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Accept');
}

if (preg_match('/\.(?:png|jpg|jpeg|gif|csv)$/', $_SERVER["REQUEST_URI"])) {
    consoleLog('info', "Transparent routing for : " . $_SERVER["REQUEST_URI"]);
    return false;
} else if (preg_match('/^.*$/i', $_SERVER["REQUEST_URI"])) {
    $filePath = "{$_SERVER['DOCUMENT_ROOT']}/{$_SERVER["REQUEST_URI"]}";
    applyCorsHeaders($CORS_ORIGIN_ALLOWED);

    if (!file_exists($filePath)) {
        consoleLog('info', "File not found Error for : " . $_SERVER["REQUEST_URI"]);
        // return false;
        http_response_code(404);
        echo "File not Found : {$filePath}";
        return true;
    }
    $mime = mime_content_type($filePath);
    // https://stackoverflow.com/questions/45179337/mime-content-type-returning-text-plain-for-css-and-js-files-only
    // https://stackoverflow.com/questions/7236191/how-to-create-a-custom-magic-file-database
    // Otherwise, you can use custom rules :
    $customMappings = [
        'js' => 'text/javascript', //'application/javascript',
        'css' => 'text/css',
    ];
    $ext = pathinfo($filePath, PATHINFO_EXTENSION);
    // consoleLog('Debug', $ext);
    if (array_key_exists($ext, $customMappings)) {
        $mime = $customMappings[$ext];
    }
    consoleLog('info', "CORS added to file {$mime} : {$filePath}");
    header("Content-type: {$mime}");
    echo file_get_contents($filePath);
    return true;
} else {
    consoleLog('info', "Not catched by routing, Transparent serving for : "
    . $_SERVER["REQUEST_URI"]);
    return false; // Let php bultin server serve
}
like image 134
Mickaël Avatar answered Sep 20 '22 09:09

Mickaël


For those of you that are still scratching your head about this, I had this same problem and figured it out. For me, proxying from the Webpack Dev Server to my PHP dev server didn't work.

It seems that the PHP built in server has problems with CORS when you use localhost for the server. Instead, you should use either your local IP address, or just 127.0.0.1, which again points to your local computer. So, you would start your server like this:

php -S 127.0.0.1:8888 -t public

Now the Webpack Dev Server proxy works. You can use 0.0.0.0 too. Hope this helps.

like image 35
AlexBet Avatar answered Sep 21 '22 09:09

AlexBet