API调用中未收到POST数据

问题描述 投票:0回答:1

我在PHP上构建了一个API。发送POST请求时,POST url中提供的变量未被接收,输入数据集为空。下面提供的数据变量create.php为空。

如果我们在创建PHP文件中提供硬编码数据,那么它工作正常。

下面是我的主要data.php文件代码。其中包含使用POST变量创建产品的功能。

<?php
class Data{
private $conn;
private $table_name = "data";
public $id;
public $email;
public $address;
public $lasttx;
public $created;
public function __construct($db){
$this->conn = $db;
}

function create(){
$query = "INSERT INTO " . $this->table_name . " SET email=:email, 
address=:address, lasttx=:lasttx, created=:created";

$stmt = $this->conn->prepare($query);

$this->email=htmlspecialchars(strip_tags($this->email));
$this->address=htmlspecialchars(strip_tags($this->address));
$this->lasttx=htmlspecialchars(strip_tags($this->lasttx));
$this->created=htmlspecialchars(strip_tags($this->created));

$stmt->bindParam(":email", $this->email);
$stmt->bindParam(":address", $this->address);
$stmt->bindParam(":lasttx", $this->lasttx);
$stmt->bindParam(":created", $this->created);

if($stmt->execute()){
return true;
  }
return false;
}

下面是在API调用中调用的create.php的代码。此文件接收数据并在data.php中调用create function

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow- 
Headers, Authorization, X-Requested-With");

include_once '../config/database.php';
include_once '../objects/data.php';

$database = new Database();
$db = $database->getConnection();

$data1 = new Data($db);

$data = json_decode(file_get_contents("php://input"), true); // THIS VARIABLE is EMPTY while calling API.

$data1->email = $data["email"];
$data1->address = $data["address"];
$data1->lasttx = $data["lasttx"];
$data1->created = date('Y-m-d H:i:s');

if($data1->create()) {
    echo '{';
        echo '"message": "Product was created."';
    echo '}';
}
else{
    echo '{';
        echo '"message": "Unable to create product."';
    echo '}';
}
?>

请指教。非常感谢。

php json api post
1个回答
1
投票

如你在评论中指出的那样,表格变量是通过URL提交的。在上面的脚本中,您正在尝试解析作为请求的有效负载的JSON对象。而这不是这些参数的位置 - 因此您不会从那里获得任何数据。

要从PHP中访问URL中的变量,您需要做的就是从$_GET数组中获取它们。例如电子邮件将在$_GET["email"]

所以这部分在这里:

$data = json_decode(file_get_contents("php://input"), true); // THIS VARIABLE is EMPTY while calling API.
$data1->email = $data["email"];
$data1->address = $data["address"];
$data1->lasttx = $data["lasttx"];
$data1->created = date('Y-m-d H:i:s');

会变成:

# $data = json_decode line goes away
$data1->email = $_GET["email"];
$data1->address = $_GET["address"];
$data1->lasttx = $_GET["lasttx"];
$data1->created = date('Y-m-d H:i:s');

希望这可以帮助

马蒂亚斯

© www.soinside.com 2019 - 2024. All rights reserved.