使用php和json构建API


Buliding an API using php and json

我有以下脚本,通过json显示数据库记录。它工作得很好。

我的问题是我如何用它创建一个安全的API,以便当用户放置API说http://www.waco.com/profile.php?id=0990999&security=xxxxxxxxx在他们的网站上,它将从我的服务器拉信息,并显示在他们的网站上。下面是整个工作代码

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
$(document).ready(function(){
    var formhtml =  "logreq=1";
    var postURL= 'profile.php';
    $.ajax({
        type: "POST",
        url: postURL,
        data: formhtml,
        dataType: JSON,
        success: function(html){
            var output= '<table class="logtable"><tbody><thead><th>Log</th><th>Username</th><th>Date</th><th>Event</th></thead>';
            var logsData = $.parseJSON(html);
            for (var i in logsData.logs){
                output+="<tr><td>" + logsData.logs[i].title + "</td><td>" + logsData.logs[i].user + "</td><td>" + logsData.logs[i].date+ "</td><td>" + logsData.logs[i].log+"</td></tr>";               
            }
            //write to container div
            $("#log_container").html(output);
        },
        error: function (html) {
            alert('Oops...Something went terribly wrong');
        }
    });
});
</script>
</head>
<body>
    <div id="log_container">
    </div>
</body>
</html>


<?php
    $db = mysqli_connect("localhost","root","","profile_database");
    //MSG
    $query = "SELECT * FROM logs LIMIT 20";
    $result = mysqli_query($db, $query);
    //Add all records to an array
    $rows = array();
    while($row = $result->fetch_array()){
        $rows[] = $row;
    }
    //Return result to jTable
    $qryResult = array();
    $qryResult['logs'] = $rows;
    echo json_encode($qryResult);
    mysqli_close($db);
?>

我需要帮助

我假设您的示例过于简化,并且您将考虑防止SQL注入以及任何额外的验证,以确保您获得预期的数据。

我将把PHP代码放在一个单独的文件中供用户调用,并将代码放入其中,如下所示:
if(isset($GET['id']) && isset($GET['security'])){
  $id = $GET['id']; $secure = $GET['security']; // TODO: escape these strings
  $db = mysqli_connect("localhost","root","","profile_database");
  //MSG
  $query = "SELECT * FROM logs LIMIT 20 Where id = $id And security = $secure";
  $result = mysqli_query($db, $query);
  //Add all records to an array
  $rows = array();
  while($row = $result->fetch_array()){
    $rows[] = $row;
  }
  //Return result to jTable
  $qryResult = array();
  $qryResult['logs'] = $rows;
  echo json_encode($qryResult);
  mysqli_close($db);
}

希望有帮助。这是一个很好的开始。我还会研究PHP框架,如CodeIgniter或Cake,它们将帮助您正确构建API。