How To Bypass Access-Control-Allow-Origin Using PHP

If you’ve ever gotten this message in the developer console:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Then here’s how to fix it, you essentially have two options. The less secure way is to just allow access from any origin, you can do that by adding this as the first line in the PHP script you’re trying to run

header('Access-Control-Allow-Origin: *');

The more secure way is to specifically define all places that you want to allow, which you can do like this, obviously substituting in your own origin domain

 header('Access-Control-Allow-Origin: http://example.com');
 header('Access-Control-Allow-Origin: http://www.example.com');
 header('Access-Control-Allow-Origin: https://m.example.com');

And thats it!

What’s Access-Control-Allow-Origin?

One way that servers prevent cross site scripting is by using what is called “Access-Control-Allow-Origin”. The most common time that you might run into this as an issue is if you’re trying to make an ajax call to a php script on another domain. For example, lets say you own two domain names, and you want to use a php script from site “A” on site “B” using ajax. So on site “A” you have something like this:

$.ajax({
	type: 'POST',
	cache: 'false',
	data: {data1:data1, data2:data2},
	url: 'http://anotherDomain.com/script.php' ,
	success: function(d) {
		alert(d)
	}
});

The script won’t run, and if you look in the developer console, you’ll see an error message. The solution is to add one of the two pieces of code listed above.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>