【问题标题】:.php not sending POST to server (GET being sent instead).php 不向服务器发送 POST(而是发送 GET)
【发布时间】:2017-07-04 20:14:49
【问题描述】:

我遇到的问题似乎是在下面的执行函数中使用 file_get_contents 发送 GET。对于我的生活,我无法弄清楚为什么。我已经使用 POST 和 Postman 测试了 api 服务器,它工作正常。

第一个函数用于传递我的请求以发送到服务器。第二个函数在我的 form_handler.php 文件中,它构建数据以通过 execute() 发送到服务器。

api_handler.php

<?php
function execute($command, $context = NULL)
{
    $url_scheme = "http://";
    if (isset($_SERVER['HTTPS']))
    {
        $url_scheme = "https://";
    }
    $url_host = $_SERVER['HTTP_HOST'];
    $url_api = "/SkedApi/";
    $url = $url_scheme.$url_host.$url_api.$command;

echo $url . "<br/>";
var_dump($context);
var_dump(headers_list());
    $response = file_get_contents($url, false, $context);
var_dump(headers_list());
echo $response;
    if ($response)
    {
        $output = json_decode($response, true);
    }
    else
    {
        $output = "error";
    }
    return $output;
}

?>

users_handler.php

$test = array ('foo' => 'bar', 'bar' => 'baz'); 
$postdata = http_build_query($test);

echo $postdata;

$opts = array (
    'http' => array (
        'method' => 'POST',
        'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
            . "Content-Length: " . strlen($postdata) . "\r\n",
        'content' => $postdata
        ));

var_dump($opts);

$context = stream_context_create($opts);

print_r($context);
$result = execute("Users", $context);

if ($result)
{
    echo "YES</br>";
}

从我的 apache 访问文件中:

::1 - - [04/Jul/2017:16:02:00 -0400] "POST /SkedApi/Users HTTP/1.0" 301 239
::1 - - [04/Jul/2017:16:02:00 -0400] "GET /SkedApi/Users/ HTTP/1.0" 200 196
::1 - - [04/Jul/2017:16:02:00 -0400] "POST /SkedAvailability/users_handler.php HTTP/1.1" 200 2688

免责声明:对所有 var_dumps 感到抱歉;

【问题讨论】:

标签: php apache http


【解决方案1】:

您的日志显示了对 POST 请求的 301 响应,然后是对同一 URL 的 200 响应,并附加了斜杠。

如果更改 users_handler.php 的这一行会发生什么

$result = execute("Users", $context);

为了这个?

$result = execute("Users/", $context);

【讨论】:

  • 成功了...所以现在我需要找出进行重定向和传递 POST 数据的最佳方法
  • 您可以为所有 POST 请求添加响应代码为 307 的重写规则。简单的选择当然只是修改你的执行函数,所以它在 $url 变量的末尾附加一个斜杠
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2016-03-08
相关资源
最近更新 更多