• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cors php issues

#1
Any one solve cors prefight strategy? My code work on localhost verey well but when test on host i got error?
Reply

#2
I add this to my root .htaccess file for CORS.

PHP Code:
    # Add Font Types
    AddType application/vnd.ms-fontobject .eot
    AddType application
/x-font-ttf        .ttf
    AddType application
/x-font-opentype   .otf
    AddType application
/font-woff         .woff
    AddType application
/font-woff2        .woff2

    
# Add Image Types
    AddType image/svg+xml .svg .svgz .jpg .png .ico

    
<IfModule mod_headers.c>
        <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|svg|svgz|jpg|png|ico|font.css|css|js)$">
            ## un-remark this one for all access and remark out the one below it            
            #Header set Access-Control-Allow-Origin "*"
            ## Change this to your local host url. and https or http
            Header add Access-Control-Allow-Origin"https://blog.local"
            Header add Access-Control-Allow-Methods"GET,POST,OPTIONS,DELETE,PUT"
            Header add Access-Control-Allow-Headers"Upgrade-Insecure-Requests"
        </FilesMatch>
    </IfModule>

    # Remove index.php from URL
    RewriteCond %{HTTP:X-Requested-With}    !^XMLHttpRequest$
    RewriteCond %{THE_REQUEST}              ^[^/]*/index\.php [NC]
    RewriteRule ^index\.php(.*)$            $[R=301,NS,L

Read the comments for the headers.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#3
Thans dude it was huge help i got stuck for day
Reply

#4
i find way to handle CORS  prefight strategy 

follow code you need middelwear(filter in ci4) to handle request before  any request send to host 
it should be global middelwear(filter in ci4)
go to path app/filters create CrosFilter.php  then add this  code 

// read  comment s  

PHP Code:
<?php namespace App\Filters;

use 
CodeIgniter\config\Services;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\Response;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CodeIgniter\Filters\FilterInterface;


class 
CorsFilter implements FilterInterface
{
    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {


    }

    public function before(RequestInterface $request$arguments null)
    {
        // get origins
        if (array_key_exists('HTTP_ORIGIN'$_SERVER)) {
            $origin $_SERVER['HTTP_ORIGIN'];
        } else if (array_key_exists('HTTP_REFERER'$_SERVER)) {
            $origin $_SERVER['HTTP_REFERER'];
        } else {
            $origin $_SERVER['REMOTE_ADDR'];
        }
        $allowed_domains = array(
            'http://localhost:4200',
            'http://www.example.com',

        );

        // this code work on real host for example  www.example.com

        $response Services::response();
        
$response->setHeader('Access-Control-Allow-Origin''www.example.com');
        $response->setHeader('Access-Control-Allow-Methods''GET, POST, OPTIONS, PUT, DELETE');
        $response->setHeader('Access-Control-Allow-Headers''Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token');
        $response->setHeader("Access-Control-Allow-Credentials""true");
        $response->setHeader('Access-Control-Max-Age''3600');
        $response->setStatusCode(Response::HTTP_OK'cors are  enable');
        $response->setContentType('application/json; charset=UTF-8');
        $response->send();

        if ($request->getMethod(true) == "OPTIONS"
        ) {
            die();

        }


        // this below code work on  localhost xammp server  localhost:8080


//        if (in_array($origin, $allowed_domains)) {
//            header('Access-Control-Allow-Origin: ' . $origin);
//        } else {
//            header('Access-Control-Allow-Origin: ' . site_url());
//        }
//
//        header("Access-Control-Allow-Headers: Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
//        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
//        header("Access-Control-Allow-Credentials: true");
//        header("Access-Control-Max-Age: 3600");
//        header('content-type: application/json; charset=utf-8');
//        $method = $_SERVER['REQUEST_METHOD'];
//        if ($method == "OPTIONS") {
//            die();
//        }


    }






then go to  this path  app/config/filters add this filter to your project  


PHP Code:
<?php

namespace Config;

use 
App\Filters\AuthFilter;
use 
App\Filters\CorsFilter;
use 
App\Filters\CsrfFilter;
use 
App\Filters\JwtFilter;
use 
App\Filters\UrlFilter;
use 
CodeIgniter\Config\BaseConfig;
use 
CodeIgniter\Filters\CSRF;
use 
CodeIgniter\Filters\DebugToolbar;
use 
CodeIgniter\Filters\Honeypot;

class 
Filters extends BaseConfig
{
    /**
     * Configures aliases for Filter classes to
     * make reading things nicer and simpler.
     *
     * @var array
     */
    public $aliases = [
        //'csrf'     => CSRF::class,
        'toolbar' => DebugToolbar::class,
        'honeypot' => Honeypot::class,
        'csrf' => CsrfFilter::class,
        'cors' => CorsFilter::class,
        'auth' => AuthFilter::class,
        'jwt' => JwtFilter::class,
        'url' => UrlFilter::class,
    ];

    /**
     * List of filter aliases that are always
     * applied before and after every request.
     *
     * @var array
     */
    public $globals = [
        'before' => [
            // 'honeypot',
            'cors',
            'url',
              'csrf',

        ],
        'after' => [
            'toolbar',
              'csrf',
            // 'honeypot',
        ],
    ];

    /**
     * List of filter aliases that works on a
     * particular HTTP method (GET, POST, etc.).
     *
     * Example:
     * 'post' => ['csrf', 'throttle']
     *
     * @var array
     */
    public $methods = [

        //  'get' => ['csrf'],
        // 'post' => ['csrf'],
        // 'put' => ['csrf'],
        // 'delete' => ['csrf']

    ];

    /**
     * List of filter aliases that should run on any
     * before or after URI patterns.
     *
     * Example:
     * 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
     *
     * @var array
     */
    public $filters = [
        'auth' => ['before' => 'api*'],
        'jwt' => ['before' => 'api*',],

    ];

Reply

#5
You should do a check for either http or https.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#6
(04-16-2021, 08:36 PM)InsiteFX Wrote: You should do a check for either http or https.
What do you mean?
Its need add this code 
PHP Code:
if (!empty($_SERVER['HTTPS'])) 
{
  echo 'https is enabled';
}
else
{
echo 
'http is enabled'."\n";


What am i gonna do with it?
Reply

#7
READ:

CORS

You have to include the http or https in the header.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#8
(04-17-2021, 06:00 AM)InsiteFX Wrote: READ:

CORS

You have to include the http or https in the header.
  Basclly you telling me header have to change  deponde on which request  received 

I got it thank dude
Reply

#9
the thing i forgot when we have front end back end separete are:

1- upload ci4 app in (create subdomain api.exmple.com) subdomain

2- upload angular (frontend app) exmple.com to work middleware with any problem on live host
otherwise when ci4 and angular area in same domain(exmple.com) it dose work and cros prefight is showing error to you
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.