Resolving Access Control Allow Origin Error using Proxy


Many of us might have faced problem while sending ajax request to an external URL. I have tried to resolve this issue by creating a proxy in PHP and using CRON to access such URL.

The problem:



Even with most common ajax request like this

We might end up with ‘Access-Control-Allow-Origin’ header error.

To allow this request made by the server of must return ‘Access-Control-Allow-Origin’ as

The Solution

To resolve this issue we will try use curl using PHP as a proxy to get required data. Your required data could be the HTML code of the site to extract some part of content or you want to know the HTTP status code for your request.

We will show you how we can proxy through PHP to get the desired result. Lets create testurl.php file first:

We will be taking website URL from $_GET  method of PHP and store it in a variable and initialize the curl.

curl_setopt($ch, CURLOPT_HEADER, true)  will get the headers.

curl_setopt($ch, CURLOPT_NOBODY, false); will get the full body which can be processed as required.

We will now save the result in our array and echo it as json. The PHP will output us a JSON which can be processed by our Ajax request.

At front end we will require jQuery, you can import it as

<script src="" charset="utf-8"></script>

Now you can put your ajax request to get the response code:

Make sure you have placed the testurl.php file that we created above in your public_html or www directory of your server.

You can customize your output for each responseCode  by assigning some task.

Alternatively, If you want to get the HTML replace result.respcode  with result.html and you can process it as per your requirement.


Please enter your comment!
Please enter your name here