Bypass CORS with PHP and Javascript / Ajax

I've been trying to figure this out for hours, although I'm too uneducated in web development to understand. Takes place:

Another website has a script that they receive information like this:

    var url = "numbers.php";
parameters = "scoreid=" + document.getElementById('whatscore').value;
parameters += "&num=" + document.getElementById('num1b1').value;

xmlhttp2=GetXmlHttpObject();
if (xmlhttp2==null) {
    alert ("Your browser does not support XMLHTTP!");
    return;
}

xmlhttp2.onreadystatechange = function() {
    if (xmlhttp2.readyState==4) {
        scorespot.innerHTML=xmlhttp2.responseText;              // load 
        setScores(document.getElementById('gradelvl').value);   // set 
        document.getElementById('submitscorebtn').style.display="none";
    }
}
xmlhttp2.open("POST",url,true);
xmlhttp2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp2.setRequestHeader("Content-length", parameters.length);
xmlhttp2.setRequestHeader("Connection", "close");
xmlhttp2.send(parameters);

      

I tried to do the same, although when I try I get a cross-origin error. I know these are ways to do it with jsonp and other things, although I don't know where to start at all for this.

When I try to directly request information from my page, at number.php page like example.com/numbers.php?scoreid=131&num=41. I always return with "Error: Invalid parameter syntax".

Can someone please tell me how I would fix this in my case? I only know PHP and Javascript, I am very uneducated with Ajax and other things or external libraries.

I appreciate all the help! NOTICE: I DO NOT ACCESS THE WEBSITE.

+3


source to share


4 answers


If you don't have access to your server configuration, and if you don't have control over the external php script (assuming it's not configured to do a reverse proxy), you absolutely can't use the standalone javascript for this.

Rather, you will have to make an external request from your own local php script. Then you call your local PHP script from Ajax and this will work since you are accessing a local file and thus don't violate CORS.

Here is an example of an Ajax call through a local PHP script.

Imagine a script that allows users to search for an album name. User enters song name and artist. You send a request to a third party api and return a response to the user via a JavaScript alert notification. For this example, suppose the user enters "black" and "Pearl Jam" as song and artist names

Ajax POST to local PHP script using HTML example:

<html>
  <head>
  <!-- Load jQuery Library from Google -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
  </head>        

  <body>
    <h1> Ajax to local PHP  Example: </h1>

    <form id="getArtist">
      Artist: <input type="text" placeholder="Pearl Jam">
      Song: <input type="text" placeholder="Black">
      <input type="submit" value="Click Here to Active Ajax Call">
    </form>

  </body>
</html>

<script type='text/javascript'>
$("#getArtist").submit(function(event) { //Listen to when the Submit is pressed
    event.preventDefault();  //Stop the submit from actually performing a submit
    $.post("local_script.php", { song: "Black", artist: "Pearl Jam", dataType: "json"}) //prepare and execute post
        .done(function(response) { //Once we receive response from PHP 
            //Do something with the response:
            alert("The album name is: " +response);
            //Look into JSON.parse and JSON.stringify for accessing data 
         });
    });
</script>

      



PHP GET

<?php
$url = 'http://api.music.com/album';

$song = urlencode($_GET['song']));    //Need to url encode
$artist = urlencode($_GET['artist']); //Need to url encode

$response = file_get_contents($url .'?song=' .$song .'&artist=' .$artist);
    //**The url looks like http://api.music.com/album?song=Black&artist=Pearl+Jam

//** For purposes of this demo, we will manually assume the JSON response from the API:
$response = '{ "album": "Ten" }'; //(Raw JSON returned by API)
echo $response; //Return the response back to AJAX, assuming it is already returned as JSON. Else encode it json_encode($response)

      

PHP POST (using curl)

<?php
$url = 'http://api.music.com/album';

$song = urlencode($_GET['song']));    //Need to url encode  
$artist = urlencode($_GET['artist']); //Need to url encode

//$headers = array("Key: " ."Value","Key: " ."Value", //Set any headers, if required.

$post = 'song=' .$song .'&artist=' .$artist; //Prepare Post parameters

/* Configure Curl */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);    
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //Allow music api to send response
curl_setopt($ch, CURLOPT_POST, 1);            //Signifyd that we are doing a POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
//curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //Only if you need to send headers


/* Get Response */
$response = curl_exec($ch);

//** For purposes of this demo, we will manually assume the JSON response from the API:
$response = '{ "album": "Ten" }'; //(Raw JSON returned by API)

echo $response; //Send response back to Ajax, assuming it was already returned in JSON. Else encode it.

      

Further reading on Ajax requests:
https://api.jquery.com/jquery.get/
https://api.jquery.com/jquery.post/

+4


source


You might find this helpful: How to send a POST request with a cross-domain domain via JavaScript?



Also, if you don't need to use POST

, you can use jsonp

(no CORS setup required)

+1


source


Your easiest solution here is to enable CORS , assuming you control the page you are trying to access, which you can do in a number of different ways detailed on this site. This error will also go away if you try to make your AJAX request from the same host as the page your Javascript code is running on - the same host in this case means the same domain (including the same subdomain).

0


source


There is no way (using XMLHttpRequest) unless you have control on the remote server

<please comment on the reason for swallowing me.

CORS introduces a standard mechanism that all browsers can use to implement cross-domain requests. The specification defines a set of headers that allow the browser and the server to exchange information about which requests (and not allowed) are allowed

Cross-site HTTP requests initiated from scripts were subject to known restrictions for well-understood security reasons. For example, HTTP requests made using the XMLHttpRequest object had a policy of the same origin. In particular, this meant that a web application using XMLHttpRequest could only make HTTP requests to the domain it was uploaded to and not to other domains.

This rule is. Even you can find a way around this, it will be fixed someday, simply because breaking the rule

0


source







All Articles