【问题标题】:PHP Script on Apache reply on Post RequestApache 上的 PHP 脚本回复发布请求
【发布时间】:2014-08-20 08:23:35
【问题描述】:

我想从我的 C# 脚本向我的本地服务器发送一个发布请求。应该有一个 PHP 脚本来回复这个 post 请求,并以 json 形式返回来自 mysql 数据库的数据。但是 PHP 脚本如何从我的客户端回复 HTTP 帖子?

【问题讨论】:

  • 因为它回复来自任何其他客户端的 HTTP 帖子。检查超全局 post 数组并使用 json_encode 回显数据或使用您希望的任何协议设置数据流。您还可以设置一个 SOAP 包装器以便于访问。
  • 你有什么网站有好的教程吗?假设我用 c# 发出了一个 post 请求,我的本地网站“http://*.*.*.*/test.php”和“thing1=test&thing2=example”之类的数据,然后我想要一个 json 字符串作为响应使用我的 mysql 数据库中的数据。但是我可以用什么样的 php 代码对这个 http 帖子做这样的回复呢?我已经知道 json_encode 函数以及它如何与 mysql 连接一起工作。
  • 这段代码可以工作吗:<?php $thing1= $_POST["thing1"]; $thing2 = $_POST["thing2"]; ?> 以便变量 $vorname 包含我的帖子请求中的数据?
  • 是的,但是您应该做一些输入验证并使用准备好的语句来查询数据库以防止 SQL 注入黑客攻击。

标签: php apache http


【解决方案1】:

如果您执行 post 请求,返回 JSON 数据的最基本设置如下:

您可以将参数用作数组:

192.*.*.*/test.php?thing[0]=test&thing[1]=example

192.*.*.*/test.php?thing[key-a]=test&thing[key-b]=example

或使用单个参数:

192.*.*.*/test.php?thing1=test&thing2=example

我推荐第一种方法,因为当您想添加更多参数时它更灵活。

<?php

if( empty( $_POST ) ) {
    // exit the script if there is no post data
    return;
}

// using parameters as array:

// filter empty values ('', 0) from array, if necessary
$_POST = array_filter( $_POST );

// reading array parameters
foreach( $_POST as $key => $value ) {

    // retrieve your parameters here
    $column = $key;
    $value = trim( $value );

    // and query the database
    $results = PDO::fetchAll( PDO::FETCH_ASSOC );

}

// output JSON; $results could be an array as retrieved through PDO::fetchAll()
echo json_encode( $results );


// or using single parameters:

if( !empty( $_POST['thing1'] ) && !empty( $_POST['thing2'] ) ) {

    // query the database
    $results = PDO::fetchAll( PDO::FETCH_ASSOC );

}

【讨论】:

  • @user3493797 我再次更新了脚本以在根本没有发布数据时退出,这通常在 PHP 世界中。 (早期函数返回优于大 else 块;这也适用于文件范围 return;
猜你喜欢
  • 1970-01-01
  • 2013-07-25
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多