使用PHP和Javascript / Ajax绕过CORS

时间:2022-12-05 13:54:13

I've been trying to figure this out for hours, though I'm too uneducated in web development to understand. Heres the case:

我一直在努力解决这个问题几个小时,虽然我在网络开发方面没有受过教育而无法理解。继承人:

Another website has a script that they obtain information from the following way:

另一个网站有一个脚本,他们从以下方式获取信息:

    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've attempted to do the same thing, though when I attempt it I get the cross-origin error. I know their are ways to do it with jsonp and other things, though I have no clue where to start at all for this.

我试图做同样的事情,但是当我尝试它时,我得到了交叉原点错误。我知道他们有办法用jsonp和其他东西来做,虽然我不知道从哪里开始为此。

When I attempt to directly request information from their page, the numbers.php page, such as example.com/numbers.php?scoreid=131&num=41 . I always get returned with "Error: incorrect parameter syntax".

当我尝试直接从他们的页面请求信息时,可以访问numbers.php页面,例如example.com/numbers.php?scoreid=131&num=41。我总是返回“错误:参数语法不正确”。

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

任何人都可以告诉我如何解决这个问题吗?我只熟悉PHP和Javascript,我很缺乏Ajax和其他东西或外部库。

I appreciate all help whatsoever! NOTICE: I DO NOT HAVE ACCESS TO THE WEBSERVER.

我感谢所有的帮助!注意:我无法访问WEBSERVER。

4 个解决方案

#1


4  

If you do not have access to your server configuration, and if you do not control the external php script (assuming it's not set up to serve as a reverse proxy), then you absolutely cannot use a standalone javascript solution for this.

如果您无法访问您的服务器配置,并且您没有控制外部PHP脚本(假设它没有设置为反向代理),那么您绝对不能使用独立的JavaScript解决方案。

Rather, you would have to make the external request from your own local php script. Then you would call your local php script from Ajax, and this will work since you are accessing a local file, and thus not violating CORS.

相反,您必须从您自己的本地PHP脚本发出外部请求。然后你可以从Ajax调用你的本地php脚本,这样你就可以访问本地文件了,因此不会违反CORS。

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

Imagine a scenario where you allow users to lookup an album name. The user enters the name of the song, and the artist. You make a request to a 3rd party api, and return the response back to the user via a JavaScript alert notification. For this example, assume the user enters 'Black' and 'Pearl Jam' as the song and artist names

以下是通过本地PHP脚本进行Ajax调用的示例。想象一下允许用户查找专辑名称的场景。用户输入歌曲的名称和艺术家。您向第三方API发出请求,并通过JavaScript警报通知将响应返回给用户。对于此示例,假设用户输入“Black”和“Pearl Jam”作为歌曲和艺术家姓名

Ajax POST to Local PHP Script with HTML Example:

使用HTML的Ajax POST到本地PHP脚本示例:

<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 Script 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 script
            //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 POST(使用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/

进一步阅读Ajax请求:https://api.jquery.com/jquery.get/ https://api.jquery.com/jquery.post/

#2


1  

This may prove useful: How do I send a cross-domain POST request via JavaScript?

这可能有用:如何通过JavaScript发送跨域POST请求?

Also, if you do not need to use POST you could use jsonp (no CORS setup required)

此外,如果您不需要使用POST,您可以使用jsonp(无需CORS设置)

#3


0  

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

这里最简单的解决方案是启用CORS,假设您控制了您尝试访问的页面,您可以通过该站点详细说明的多种方式进行操作。如果您尝试从与运行Javascript代码的页面相同的主机发出AJAX请求,此错误也将消失 - 在这种情况下,同一主机意味着来自同一个域(包括相同的子域)。

#4


0  

There is NO WAY (using XMLHttpRequest), If you have no control to the remote server

没有办法(使用XMLHttpRequest),如果您无法控制远程服务器

< comment me the reason for down vote please.

<请注意我投票的原因。< p>

CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed

CORS引入了一种标准机制,可供所有浏览器用于实现跨域请求。规范定义了一组标头,允许浏览器和服务器就允许(和不允许)哪些请求进行通信

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

出于易于理解的安全原因,从脚本内发起的跨站点HTTP请求受到众所周知的限制。例如,使用XMLHttpRequest对象进行的HTTP请求受同源策略的约束。特别是,这意味着使用XMLHttpRequest的Web应用程序只能向其加载的域发出HTTP请求,而不能向其他域发出HTTP请求。

That's the rule. Even you may find a way to bypass that, it will be fixed some day, simply because that's a violation of the rule

这是规则。即使你可能找到一种绕过它的方法,它有一天会被修复,只是因为这违反了规则

#1


4  

If you do not have access to your server configuration, and if you do not control the external php script (assuming it's not set up to serve as a reverse proxy), then you absolutely cannot use a standalone javascript solution for this.

如果您无法访问您的服务器配置,并且您没有控制外部PHP脚本(假设它没有设置为反向代理),那么您绝对不能使用独立的JavaScript解决方案。

Rather, you would have to make the external request from your own local php script. Then you would call your local php script from Ajax, and this will work since you are accessing a local file, and thus not violating CORS.

相反,您必须从您自己的本地PHP脚本发出外部请求。然后你可以从Ajax调用你的本地php脚本,这样你就可以访问本地文件了,因此不会违反CORS。

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

Imagine a scenario where you allow users to lookup an album name. The user enters the name of the song, and the artist. You make a request to a 3rd party api, and return the response back to the user via a JavaScript alert notification. For this example, assume the user enters 'Black' and 'Pearl Jam' as the song and artist names

以下是通过本地PHP脚本进行Ajax调用的示例。想象一下允许用户查找专辑名称的场景。用户输入歌曲的名称和艺术家。您向第三方API发出请求,并通过JavaScript警报通知将响应返回给用户。对于此示例,假设用户输入“Black”和“Pearl Jam”作为歌曲和艺术家姓名

Ajax POST to Local PHP Script with HTML Example:

使用HTML的Ajax POST到本地PHP脚本示例:

<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 Script 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 script
            //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 POST(使用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/

进一步阅读Ajax请求:https://api.jquery.com/jquery.get/ https://api.jquery.com/jquery.post/

#2


1  

This may prove useful: How do I send a cross-domain POST request via JavaScript?

这可能有用:如何通过JavaScript发送跨域POST请求?

Also, if you do not need to use POST you could use jsonp (no CORS setup required)

此外,如果您不需要使用POST,您可以使用jsonp(无需CORS设置)

#3


0  

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

这里最简单的解决方案是启用CORS,假设您控制了您尝试访问的页面,您可以通过该站点详细说明的多种方式进行操作。如果您尝试从与运行Javascript代码的页面相同的主机发出AJAX请求,此错误也将消失 - 在这种情况下,同一主机意味着来自同一个域(包括相同的子域)。

#4


0  

There is NO WAY (using XMLHttpRequest), If you have no control to the remote server

没有办法(使用XMLHttpRequest),如果您无法控制远程服务器

< comment me the reason for down vote please.

<请注意我投票的原因。< p>

CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed

CORS引入了一种标准机制,可供所有浏览器用于实现跨域请求。规范定义了一组标头,允许浏览器和服务器就允许(和不允许)哪些请求进行通信

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

出于易于理解的安全原因,从脚本内发起的跨站点HTTP请求受到众所周知的限制。例如,使用XMLHttpRequest对象进行的HTTP请求受同源策略的约束。特别是,这意味着使用XMLHttpRequest的Web应用程序只能向其加载的域发出HTTP请求,而不能向其他域发出HTTP请求。

That's the rule. Even you may find a way to bypass that, it will be fixed some day, simply because that's a violation of the rule

这是规则。即使你可能找到一种绕过它的方法,它有一天会被修复,只是因为这违反了规则