Resolving Access Control Allow Origin Error using Proxy

0
81

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 stackoverflow.com the server of google.com must return ‘Access-Control-Allow-Origin’ as http://www.stackoverflow.com.

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="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" 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.

SHARE
Next articleAdding custom admin bar menu item

Ashish Patel is Full Stack Web Developer & Tech Enthusiast. He loves to share his work and would be happy to contribute to any open source project.

LEAVE A REPLY

Please enter your comment!
Please enter your name here