我编写了一个php脚本,用于学习如何创建REST API。但是代码中存在一些我无法弄清楚的问题。
这是PHP脚本:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
// Get data
$name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : "";
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
$status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";
$length = strlen($status);
if( $length >= 10 ) {
$json = array("status" => 1, "name" => $name, "email" => $email, "status" => $status);
}
else {
$json = array("status" => 0, "msg" => "Error: Status too short!", "length" => $length);
}
}
else {
$json = array("status" => 0, "msg" => "Error: Request method not accepted");
}
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
我是在Mozilla Firefox的Httprequester中使用网址“http://localhost/RESTTEST.php?name=dparua&email=d.parua%40gmail.com&pwd=something&status=very%20very%20long%20status”来调用它的。
但这是我得到的回应,不管我传递的状态有多长。 “{”status“:0,”msg“:”错误:状态太短!“,”长度“:0}”
我尝试将代码更改为:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$json = array("status" => 1, "name" => $_POST['name'], "email" => $_POST['email'], "status" => $_POST['status']);
}
else {
$json = array("status" => 0, "msg" => "Error: Request method not accepted");
}
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
并发布到此修改后的脚本,这是我收到的错误消息:
“
注意:未定义索引: C:\ xampp \ htdocs \ RESTTEST.php 中 5 的名称
通知:未定义的索引: C:\ xampp \ htdocs \ RESTTEST.php 中的电子邮件 5 上的电子邮件
注意:未定义索引: C:\ xampp \ htdocs \ RESTTEST.php 中 5 行的状态
{ “状态”:空, “姓名”:NULL, “电子邮件”:NULL}“
请说明出了什么问题。
答案 0 :(得分:0)
<强> P.S。 mysql_real_escape_string - 在PHP 5.5.0中已弃用,在PHP 7.0.0中已被删除。相反,应该使用MySQLi或PDO_MySQL扩展。
在这里,您将找到可用的PHP代码(但更改登录名和密码):
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
mysql_connect('localhost', 'root', 'password') OR die(mysql_error());
// Get data
$name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : "";
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
$status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";
$length = strlen($status);
if( $length >= 10 ) {
$json = array("status" => 1, "name" => $name, "email" => $email, "status" => $status);
}
else {
$json = array("status" => 0, "msg" => "Error: Status too short!", "length" => $length);
}
}
else {
$json = array("status" => 0, "msg" => "Error: Request method not accepted");
}
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
之后安装POSTMAN应用程序。并尝试发送该请求: