如何使用PHP代理隐藏API密钥

我建立了一个显示当前天气的页面。有用。但是在发布它之前,我意识到我需要以某种方式隐藏api键。因此,我正在使用jquery ajax将发布请求发送到php文件,该文件将位于网络服务器上的安全文件夹中。然后,php文件将发送添加了api密钥的get请求,并将天气数据返回给js脚本并将其呈现到页面。我已经一起整理了一些我认为可以工作的东西,但是我认为php脚本没有从发布请求中接收任何数据。我在$ _POST变量和$ REQUEST变量上尝试了var_dump。我所得到的只是一个空数组。 js脚本从php脚本中记录了看起来像数组的东西,但是我认为这只是js从发送的字符串中构成数组?此外,我已经注释掉了返回任何内容的php脚本中的语句。有人可以帮我弄清楚我做错了什么吗?我已经在下面发布了php,js和html。谢谢!

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">



<style>
body {

  background: black;


}
.top-buffer {
  margin-top:200px;
  padding:0;

  clear: both;
}
.bottom-buffer {
  margin-bottom:50px;
}
</style>
</head>
<body>
   <div class="container">
    <div class="row">
      <div class="col-md-6 offset-md-3">


      <div class="card text-center">
<div class="card-header" id="button-header">
  <button id="celsius" class="btn btn-light float-md-right">&#x2103</button>
  <button id="fahrenheit" class="btn btn-dark float-md-right">&#x2109</button>

        </div>

        <div class="card-body" id="weather-card"> 

            <h3 id="location" class="card-title"></h3>
            <h1 id="temp"><sup>&#x2109</sup></h1>
            <h1 id="description"></h1>
            <img src="", alt="" id="weather-icon">


        </div>
      </div>
      </div>

 </div>
    </div> 

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>


<!-- Latest compiled and minified JavaScript 
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>-->

    <script src="script.js">    </script>
  </body>
  </html>
     var weatherAPI = "https://api.openweathermap.org/data/2.5/weather?";

     function getWeather(pos) {

var dataString="lat=" + pos.coords.latitude+"&lon=" + pos.coords.longitude;
console.log(dataString);

$.ajax({
method: "POST",
url: "getweatherdata.php",
data: dataString
//dataType:"text"

      })
       .done(function(data) {
          // alert("result: " + data);
          console.log("data: " + data);
        weather = data;
        //console.log(weather);

        var tempf=Math.floor(9/5*(weather.main.temp - 273.15)+32);
        var tempc=Math.floor(weather.main.temp - 273.15);
        $("#location").html(weather["name"]);
        $("#temp").prepend(tempf);
        $("#description").html(weather["weather"][0]["description"]);
        $("#weather-icon").html(weather["weather"][0]["description"]);
        $("#celsius").on("click", function() {
          $("#temp").html(tempc + '<sup>&#x2103</sup>');
          $("#celsius").removeClass("btn-light").addClass("btn-dark");
          $("#fahrenheit").removeClass("btn-dark").addClass("btn-light");


        });
        $("#fahrenheit").on("click", function() {
          $("#temp").html(tempf + '<sup>&#x2109</sup>');
          $("#celsius").removeClass("btn-dark").addClass("btn-light");
          $("#fahrenheit").removeClass("btn-light").addClass("btn-dark");



        });
        var weatherID = weather["weather"][0]["id"];
        switch (true) {
          case weatherID >= 200 && weatherID < 233: //thunderstorm
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/11d@2x.png");
          break;
          case weatherID >= 300 && weatherID <= 321: //drizzle
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/09d@2x.png");
          break
          case weatherID >= 500 && weatherID <= 504: //light rain,moderate rain,heavy intensity rain,very heavy rain,extreme rain
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/10d@2x.png");
          break;
          case weatherID == 511: //freezing rain
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/13d@2x.png");
          break;
          case weatherID >= 520 && weatherID <= 531: //light intensity shower rain,shower rain,heavy intensity shower rain,ragged shower rain
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/09d@2x.png");
          break;
          case weatherID >= 600 && weatherID <=622 : //snow
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/13d@2x.png");
          break;
          case weatherID >= 701 && weatherID <= 781: //Atmosphere
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/50d@2x.png");
          break;
          case weatherID == 800 : //clear sky
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/01d@2x.png");
          break;
          case weatherID == 801: //few clouds
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/02d@2x.png");
          break;
          case weatherID == 802: //scattered clouds
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/03d@2x.png");
          break;
          case weatherID == 803 || weatherID == 804: //broken clouds,overcast clouds
          $("#weather-icon").attr("src", "http://openweathermap.org/img/wn/04d@2x.png");
          break;


        }

      })
        .fail(function( jqxhr, textStatus, error ) {
        var err = textStatus + ", " + error;
        console.log( "Request Failed: " + err );
      });    

 }

     $(document).ready(function() {
      navigator.geolocation.getCurrentPosition(getWeather);      

    });  
<?php

//$rest_json = file_get_contents("php://input");
//$_POST = json_decode($rest_json, true);

var_dump($_POST);

//Get event ID you want to request:
//$data = isset($_POST['lat']) ? $_POST['lon'] : FALSE;

//Exit if no ID provided:
/*  if (!$data) {
    exit('No ID Provided.');
}  */
//echo $test->data;
//$lon=$_POST["lon"];

//Set your token:
//$appid = '49a090f8fd32a555bd97635debc34855';

//Set url, %s will be replaced later:
//$url = 'https://api.openweathermap.org/data/2.5/weather?'. 'lat=' .$lat .'&lon='.$lon.'&appid='.$appid;

//Set url, pass in params:
//$request_uri = sprintf($url, $lat, $lon, $appid);

//Try to fetch:
//$response = file_get_contents($request_uri);

//Set content-type to application/json for the client to expect a JSON response:
//header('Content-type: application/json');

//Output the response and kill the scipt:
//exit($response);

// header('Content-Type: application/json; charset=utf-8');

//$api_key = 'xyz1234';
//$result = array('status'=>'Error','msg'=>'Invalid parameters');

//your code to sanitize and assign (Ajax) post variables to your PHP variables
//if invalid:   exit(json_encode($result));

//make API request with $api_key
//$url = 'https://api.openweathermap.org/data/2.5/weather?' . $api_key . '&item=' . $item . '&qty=' . $qty;
/* $ch = curl_init($url);  
curl_setopt($ch,CURLOPT_FAILONERROR, TRUE);  // identify as error if http status code >= 400
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);  // returns as string
$api_response = curl_exec($ch);
if(curl_errno($ch) || curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200 ) :
    $result['msg'] = 'Item not found or unable to get data. ' . curl_error($ch);
    curl_close($ch);
    exit(json_encode($result));
endif;
curl_close($ch); */
//$decodedData = json_decode($api_response);
//print $url;
//check for success and do any server side manipulation of $decodedData

//$result['status'] = 'OK';
//$result['msg'] = '$decodedData';
//exit(json_encode($result));

?>
评论
骨感美~
骨感美~

Since you are doing a POST request you should send the data in the body request


var data = { lat: pos.coords.latitude, lon: pos.coords.longitude };

$.ajax({
method: "POST",
url: "getweatherdata.php",
data: data
//dataType:"text"
点赞
评论