I am trying to post form data from www.siteone.com to www.sitetwo.com via CORS. My ajax code is this:
<script>
$(document).ready(function(){
$("#submit").live('click',function() {
var url = "http://www.sitetwo.com/cors.php";
var data = $('#form').serialize();
jQuery.ajax({
url : url,
type: "POST",
data : $('#form').serialize(),
}).done(function(response){
alert(response);
}).fail(function(error){
console.log(error.statusText);
});
return false;
});
});
</script>
and the file cors.php in www.sitetwo.com is as follows:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
echo "hai";
?>
But still Access-control-Allow-Origin error is thrown.
The error thrown is this:
XMLHttpRequest cannot load http://www.sitetwo.com/cors.php. Origin http://www.siteone.com is not allowed by Access-Control-Allow-Origin.
I came to know that, using CORS by just allowing the remote website via headers, we can use cross-domain request. But when I tried like this, error is thrown. Have I missed anything in here?
Here is my request/response headers:
Response Headers
Connection Keep-Alive
Content-Length 487
Content-Type text/html; charset=iso-8859-1
Date Fri, 23 Aug 2013 05:53:20 GMT
Keep-Alive timeout=15, max=99
Server Apache/2.2.15 (CentOS)
WWW-Authenticate Basic realm="Site two Server - Restricted Area"
Request Headers
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length 43
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Host www.sitetwo.com
Origin http://www.siteone.com
Referer http://www.siteone.com/index.html
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0
In web development, the htaccess file plays a crucial role in configuring and securing websites. However, sometimes the server’s CORS policy can block access to resources from different origins. This issue often presents itself with the error message: “No ‘Access-Control-Allow-Origin’ header is present on the requested resource.” In this article, we’ll explore how to fix this problem using PHP code.
How to Fix PHP CORS Policy Error: No ‘Access-Control-Allow-Origin’ in the Context of htaccess File for Web Development
To fix the PHP CORS policy error “No ‘Access-Control-Allow-Origin’ in the context of htaccess file for web development”, you can add the following code to your .htaccess file:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
This will allow cross-origin resource sharing (CORS) and allow requests from any origin. You can modify the values in the “Access-Control-Allow-Headers” directive to allow specific headers if needed.
It’s important to note that enabling CORS can potentially open up your server to security vulnerabilities, so make sure to properly secure your server beforehand.
Fix CORS Error [SOLVED] | React Tutorial
What is CORS? | Fixing CORS errors in ASP.NET Core
What is the process to enable cross-origin in PHP?
To enable cross-origin in PHP, you can add the following code to your .htaccess file:
Header set Access-Control-Allow-Origin “*”
This code sets the Access-Control-Allow-Origin header to allow requests from any origin. If you only want to allow requests from specific origins, you can replace the “*” with a comma-separated list of allowed origins.
You should also add the following code to handle preflight requests:
Header set Access-Control-Allow-Methods “GET, POST, OPTIONS”
Header set Access-Control-Allow-Headers “Content-Type”
This code sets the Access-Control-Allow-Methods header to allow GET, POST, and OPTIONS requests, and the Access-Control-Allow-Headers header to allow the Content-Type header.
Enabling cross-origin access can be useful if you are building APIs or if you are serving resources from a different domain than your main website. However, be aware that it can also introduce security risks, so make sure to implement it only when necessary and with caution.
What is the solution to fix cross-origin request blocked issue in PHP?
To fix the cross-origin request blocked issue in PHP, you can add the following code to your htaccess file:
Header set Access-Control-Allow-Origin “*”
This line of code will allow requests from any origin to access your PHP scripts. However, if you want to limit access to specific origins, you can replace the asterisk (*) with the URLs of the origins you want to allow.
Note that this solution should only be used if you are certain that allowing cross-origin requests does not pose a security risk for your website or application. In some cases, it may be better to handle cross-origin requests on the server-side with PHP code instead of using htaccess.
How does Access-Control-Allow-Origin work in PHP?
In htaccess file for web development, Access-Control-Allow-Origin is a response header that indicates which domains are allowed to access the resource. When a web server receives a request from a domain outside of its domain, it will check the Access-Control-Allow-Origin header and either allow or deny the request.
In PHP, you can set the Access-Control-Allow-Origin header using the header() function. For example, to allow all domains to access a resource, you would use the following code:
“`php
header(“Access-Control-Allow-Origin: *”);
“`
The asterisk (*) allows any domain to access the resource. If you want to restrict access to specific domains, you can specify them in the header like this:
“`php
header(“Access-Control-Allow-Origin: https://example.com”);
“`
In this case, only https://example.com will be allowed to access the resource. You can also specify multiple domains by separating them with commas:
“`php
header(“Access-Control-Allow-Origin: https://example.com, https://example2.com”);
“`
In this case, both https://example.com and https://example2.com will be allowed to access the resource. It’s important to note that if you are using authentication or cookies, you need to use more complex headers to ensure proper security.
What is the solution for CORS error and how does the Access-Control-Allow-Origin header function?
Solution for CORS error in htaccess file for web development:
CORS errors occur when the browser blocks a web page from making AJAX requests to a different domain than the one that served the web page. This security feature prevents malicious scripts from making unauthorized requests to another domain, also known as cross-site request forgery (CSRF).
The solution to this problem is to set the Access-Control-Allow-Origin header in the server’s response. This header indicates which domains are allowed to access the resource. For example, if a web page served from “http://example.com” wants to make AJAX requests to “http://api.example.com”, the “http://api.example.com” server needs to include the following header in its response:
“`
Access-Control-Allow-Origin: http://example.com
“`
This allows the browser to make AJAX requests from the “http://example.com” domain to the “http://api.example.com” domain. If the server doesn’t include this header, the browser will block the AJAX request and report a CORS error.
To set this header in htaccess file, add the following line of code:
“`
Header set Access-Control-Allow-Origin “http://example.com”
“`
Replace “http://example.com” with the domain you want to allow AJAX requests from.
In summary, the Access-Control-Allow-Origin header is used to specify which domains are allowed to access resources on a server, and including it in the server’s response can solve CORS errors when making AJAX requests to a different domain.
How can I add the necessary headers to my htaccess file to enable cross-origin resource sharing (CORS) for PHP?
To enable CORS for PHP using the htaccess file, you need to add the following headers:
# Enable cross-origin resource sharing
Header set Access-Control-Allow-Origin “*”
Header set Access-Control-Allow-Headers “Origin, X-Requested-With, Content-Type, Accept”
# Enable caching of CORS preflight responses for 1 day
Header set Access-Control-Max-Age 86400
# Allow cross-origin requests for GET, POST, and OPTIONS requests
Header set Access-Control-Allow-Methods “GET, POST, OPTIONS”
# Allow credentials to be included in cross-origin requests (required for cookies, authorization headers, etc.)
Header set Access-Control-Allow-Credentials true
# Add any additional headers that your application requires
Header set Cache-Control “no-cache”
These headers allow cross-origin requests from any origin, with caching of preflight responses for one day. They also allow GET, POST, and OPTIONS requests, and include credentials in requests. You can add additional headers as needed for your specific application.
Note that these headers may not be necessary for all PHP applications, and enabling CORS can have security implications. Use caution and consult with a security professional before implementing CORS in a production environment.
Why am I receiving a “no ‘access-control-allow-origin’ header is present on the requested resource” error in my web development project and how can I fix it using htaccess?
The “no ‘access-control-allow-origin’ header is present on the requested resource” error occurs when a web application makes a request to a different domain, and that domain does not allow cross-origin requests. This is a security feature implemented in modern web browsers.
To fix this error using htaccess, you can add the following line of code to your .htaccess file:
Header set Access-Control-Allow-Origin “*”
This line of code adds the “Access-Control-Allow-Origin” header to all responses from your server, allowing cross-origin requests from any domain. Of course, you can replace the asterisk with a specific domain if you only want to allow requests from a certain domain.
It’s important to note that adding this header can potentially expose security vulnerabilities, so be sure to only use it if it’s absolutely necessary for your web application.
Is it possible to set specific CORS rules within the htaccess file for my PHP application, or do I need to modify my server configuration?
Yes, it is possible to set specific CORS rules within the htaccess file for your PHP application. CORS (Cross-Origin Resource Sharing) is a mechanism that allows web applications to access resources from a different domain. To enable CORS for your PHP application, you can add the following code to your htaccess file:
“`
Header set Access-Control-Allow-Origin “*”
Header set Access-Control-Allow-Methods “GET, POST, PUT, DELETE, OPTIONS”
Header set Access-Control-Allow-Headers “Content-Type, Authorization”
“`
This code sets the Access-Control-Allow-Origin header to “*”, which means that the resource can be accessed from any domain. You can modify this to restrict access to specific domains by changing the value of the header.
The Access-Control-Allow-Methods header specifies which HTTP methods are allowed for the resource. In this example, GET, POST, PUT, DELETE, and OPTIONS methods are allowed. You can modify this to restrict the allowed methods according to your needs.
The Access-Control-Allow-Headers header specifies which HTTP headers are allowed for the resource. In this example, only the Content-Type and Authorization headers are allowed. You can modify this to allow additional headers as needed.
It’s important to note that these headers can also be set in the server configuration. However, setting them in the htaccess file provides more flexibility because it allows you to set different CORS rules for different directories or files within your application.
In conclusion, implementing the Access-Control-Allow-Origin header in your PHP scripts is crucial for allowing cross-origin resource sharing. It can prevent errors such as “No ‘Access-Control-Allow-Origin’” from occurring and ensure that your web application runs smoothly. Additionally, adding this header to your .htaccess file is a simple and effective way to apply it site-wide. By taking these steps, you can enhance the security and usability of your web development projects.
This is a short guide on how to fix Access-Control-Allow-Origin issues when you are sending Ajax requests. In this article, I will explain why it is happening and what you can do to prevent it.
Take a look at the following example.
<!DOCTYPE html>
<html lang="en">
<head>
<title>No 'Access-Control-Allow-Origin' header</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$.ajax({
url: 'https://google.com'
});
</script>
</body>
</html>
In the example above, we attempt to send a simple Ajax request to Google using the JQuery library. However, if you run the JavaScript above, you will notice that the Ajax request fails. Furthermore, the developer console will display the following error.
Failed to load https://google.com/ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost’ is therefore not allowed access.
This error message is essentially telling us that we do not have permission to carry out an Ajax request to Google. Why? Because it is a cross-domain request and Google has not given us permission to do so.
Although you can easily embed images and videos, etc, from other websites – Ajax requests are a completely different ball game. Ajax requests are governed by something called a CORS policy. If this policy did not exist, then websites could potentially exploit Ajax requests to access sensitive information on other websites that the user is logged into.
How to fix this error.
If you own the website that you are attempting to make an Ajax request to, then you can whitelist the domain that is making the request.
Let’s say that you have a website called example.com and another website called site-a.com.
For whatever reason, you want to be able to make Ajax requests to example.com from site-a.com. On example.com, you will need to whitelist site-a.com by using the Access-Control-Allow-Origin header.
By using this header, you are telling the browser that site-a.com has permission to make cross-domain requests to your website.
PHP example.
Take the following PHP example.
//Set Access-Control-Allow-Origin with PHP
header('Access-Control-Allow-Origin: http://site-a.com', false);
In the PHP code above, we are telling the browser that site-a.com has permission to make cross-domain requests to our server.
Note that you may also come across examples like this on the web.
//Access-Control-Allow-Origin header with wildcard.
header('Access-Control-Allow-Origin: *');
In the PHP code above, we have used a wildcard character. The problem with this is that it will allow everybody to make Ajax requests to our website. This is a lazy solution that can introduce security risks.
Workaround.
If you need to scrape data from another website using Ajax and that website has not given you the permission to do so, then you will need to create a “go-between script” on your server.
For example, you could potentially create a PHP script that sends a GET request to the website in question and then outputs the response. That way, you can send Ajax requests to your “go-between script” instead of trying to get around the CORS policy.
However, this method will not work if authentication is required.
I am making a web app with Vue.js, in this web app people have to log in in order to receive an API key. I am making a post request to my API using axios, i am also sending 2 parameters with it, a name and a password. Whenever i submit my form it keeps giving me these errors:
OPTIONS http://localhost/Leerjaar%203/api/apikey/ 500 (Internal Server Error)
and
Access to XMLHttpRequest at 'http://localhost/Leerjaar%203/api/apikey/' from origin 'http://localhost:8082' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I have been stuck with this issue for months now, i stopped trying months ago but today i decided to get back to it and try again. I have tried setting the headers in my PHP file, but that doesnt seem to work either.
The method that makes the post request:
formSubmit(e) {
e.preventDefault();
let currentObj = this;
axios.post('http://localhost/Leerjaar%203/api/apikey/', {
docent: this.docentNaam,
wachtwoord: this.wachtwoord
})
.then(function (response) {
currentObj.output = response.data;
console.log(response.data);
})
.catch(function (error) {
});
}
My PHP API:
<?php
session_start();
include "../errors.inc.php";
include "../credentials.inc.php";
include "../database.inc.php";
$docent = Docent();
if (!isset($_POST["wachtwoord"])) fout(400, "wachtwoord ontbreekt");
if ($_POST["wachtwoord"] !== "test") fout(401, "wachtwoord incorrect");
header('Access-Control-Allow-Origin: http://http://localhost:8081/', false);
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
header('content-type: application/json; charset=utf-8');
echo '{"apikey":"'.md5(md5($docent)).'"}';
My form:
<form @submit="formSubmit">
<div class="form-group">
<label for="docentNaam">Naam:</label>
<input v-model="docentNaam" type="text" class="form-control" placeholder="Docenten afkorting">
<label for="wachtwoord">Wachtwoord</label>
<input v-model="wachtwoord" type="password" class="form-control" placeholder="Wachtwoord">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
This is the header i get back:
I hope someone can help me with my problem, i feel like i have tried everything.
Hi I have done all the «before you start tasks and checks»
Error in cosole log:
Access to fetch at ‘http://127.0.0.1:8000/register’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
Network Request:
\config\cors.php
return [
'paths' => ['api/*', 'register', 'oauth/*'],
'allowed_methods' => ['OPTIONS,POST,PUT,DELETE,GET'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => ['*'],
'max_age' => 0,
'supports_credentials' => true,
];
Kernel.php
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
I have tried as many combinations of the above as I can spent about 6 hours on it now with no success, your help would be greatly appreciated.
thanks
Dan
I built a new Laravel app and copied over all the code and it worked.
@danbdex did you figure what the issue was exactly? I have CORS issues for 2 days now, Axios gets 200 response and data from Laravel, but error is returned about the CORS headers missing and catch block is fired so I can get the data normally (but i see the data inside the xhr request in dev tools). I have the same Kernel.pohp and cors.php as you above …
I also encountered the same issue, upgraded from Laravel 5.7 to 7.x. It seems after upgrading it is not automatically added to the project folder.
So, I added composer require fruitcake/laravel-cors and protected $middleware = [ \Fruitcake\Cors\HandleCors::class, // ... ]; in app/Http/Kernel.php and also created cors.php inside config folder.
config file
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
// 'allowed_origins' => ['http://127.0.0.1:8080/', 'http://localhost:8080/'], <-- doesn't work, still gets CORS error
'allowed_origins' => ['*'], // <-- it works but it should not be like that
'allowed_origins_patterns' => [],
'allowed_headers' => ['content-type', 'accept', 'x-custom-header', 'Access-Control-Allow-Origin'],
// 'allowed_headers' => ['*'],
'exposed_headers' => ['x-custom-response-header'],
'max_age' => 0,
'supports_credentials' => false,
];
So, I am still wondering how it works completely. Any insight is appreciated.
Same problem, it seems like the config/Cors file is totally ignore even though I’ve puged the cache (php artisan config:cache)
Ok, some things here. I’m using Nuxt as a client and I there was a part of my url that was missing ‘/api/’. So it looks like when there is a mistake in the url you get the cors response. But that does not explains all, after correcting the url i’d get the same error. So I commented out the fruitcake middleware part of the kernel.file and added one cors file found somewhere…but not using the provided cors extension. That still did not the trick. So, i’ve found on stackoverflow this piece of code
header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: *'); header('Access-Control-Allow-Headers: Origin, X-Requested-With,Authorization, Content-Type, Accept');
that I’ve added at the top of the app.php file inside the bootstrap folder. And that made it work. It was a fresh install with passport.
anyone coming here, please try php artisan config:cache after any changes. That was the problem with my setup. may it save you few hours.
tinycoding5, Gaan123, suhaboncukcu, stewis, JonathanVelkeneers, ahmedgadit, devkea, Kacpers, alintuhut, aren1989, and 10 more reacted with thumbs down emoji
yc-codes, MrEldin, and Ham3D reacted with hooray emoji
kevin-kirsten, Goddarna, ftgk, kmihiranga, staqd, voitsekhovskymax, Mohamed-Ali-Nakouri, jakew009, yc-codes, MrEldin, and 2 more reacted with heart emoji
MrEldin, Ham3D, and cryptiswap-admin reacted with rocket emoji
You can add into TrustHosts.php Middleware without doing anything extra.
// app/Http/Middleware/TrustHosts.php public function hosts() { return [ $this->allSubdomainsOfApplicationUrl(), 'https://www.nexgi.com' ]; }
The above code is working well in laravel 8.x and if you are running queue or supervisorctl then restart to reflect the changes.
Adding to this: the cors headers are sent on the way back up the middleware stack, if you have any debug & die/ flow breaks in your controllers or any other place before the stack, the headers will not be added.
anyone coming here, please try
php artisan config:cacheafter any changes. That was the problem with my setup. may it save you few hours.wasted 3 hours here …. also tried clearing config cache and still no success. thanks \m/
same to me, try to config in both Laravel and nginx but no luck
None of above solutions works for me.
Have laravel 8 and vue js.
None of above solutions works for me.
Have laravel 8 and vue js.
Check your logs, there are times that there is a 500 problem but laravel shows cors( the cors config are not loaded yet) problem
To fix this problem I had to add a path to my cors.php
I changed:
'paths' => [],
to:
'paths' => ['*'],
dont forget about apache module LoadModule headers_module modules/mod_headers.so
To Fix this problem I had run this command
sudo php artisan config:cache
For bitnami/laravel/ docker user who wants to add CORS header to static resources(images in my case):
No hope folks, dirty workarounds are the only solutions :S
I tought somehow I can change nginx/apache configuration, but it turns out that this image uses the following artisan command:
php artisan serve --host=0.0.0.0 --port=8000
And I find no options to add CORS headers.
Note:
For php related url-s, the following solutions will work:
config/cors.php
Update config/cors.php, then run php artisan config:cache
headers in index.php
Add the following lines to public/index.php:
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Headers: content-type');
Add this into your .htaccess which is located with your index.php
and
Change domain name with your website name in below code(Header add Access-Control-Allow-Origin: «https://typeHEREyour.com»)
Code:
For CORS Configuration
# 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
<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://typeHEREyour.com"
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(.*)$ $1 [R=301,NS,L]
I also encountered the same issue, upgraded from Laravel 5.7 to 7.x. It seems after upgrading it is not automatically added to the project folder.
So, I added
composer require fruitcake/laravel-corsandprotected $middleware = [ \Fruitcake\Cors\HandleCors::class, // ... ];inapp/Http/Kernel.phpand also createdcors.phpinsideconfig folder.config file
return [ 'paths' => ['api/*'], 'allowed_methods' => ['*'], // 'allowed_origins' => ['http://127.0.0.1:8080/', 'http://localhost:8080/'], <-- doesn't work, still gets CORS error 'allowed_origins' => ['*'], // <-- it works but it should not be like that 'allowed_origins_patterns' => [], 'allowed_headers' => ['content-type', 'accept', 'x-custom-header', 'Access-Control-Allow-Origin'], // 'allowed_headers' => ['*'], 'exposed_headers' => ['x-custom-response-header'], 'max_age' => 0, 'supports_credentials' => false, ];So, I am still wondering how it works completely. Any insight is appreciated.
Is this package for API routes only?


