【问题标题】:How to send POST data through PHP [duplicate]如何通过PHP发送POST数据[重复]
【发布时间】:2014-04-12 10:21:39
【问题描述】:

我在同一目录下的 Web 服务器上有 2 个文件:post.php 和 receive.php

post.php 文件发布用户名和密码。 receive.php 接收用户名和密码,并打印出来。

receive.php 文件如下所示:

<?php
    $user=$_POST["user"];
    $password=$_POST["password"];
    echo("The Username is : ".$user."<br>");
    echo("The Password is : ".$password."<br>");
?>

我有这个 post.php 的代码:

<?php
    $r = new HttpRequest('http://localhost/receive.php', HttpRequest::METH_POST);
    $r->addPostFields(array('user' => 'mike', 'password' => '1234'));
    try {
        echo $r->send()->getBody();
    } catch (HttpException $ex) {
        echo $ex;
    }
?>

我尝试了各种不同的编码 post.php 文件的方法,但都没有奏效。我也尝试过在线学习一些教程,但这也不起作用。我是PHP菜鸟,请帮忙!!

【问题讨论】:

  • 请将post.php的内容发布到您的问题中
  • 你试过用 curl 吗?
  • @Pattle 我刚刚发布了“post.php”的代码
  • @rakeshjain 我没用curl,只是想用PHP自带的函数来完成这个
  • 您的代码没有问题,并且可以正常工作。问题一定出在服务器配置上。

标签: php http post httprequest


【解决方案1】:

post.php 的以下代码对我有用。我不是 100% 确定它的作用,但它确实有效。

<?php
$params = array ('user' => 'Mike', 'password' => '1234');

$query = http_build_query ($params);

// Create Http context details
$contextData = array ( 
            'method' => 'POST',
            'header' => "Connection: close\r\n".
                        "Content-Length: ".strlen($query)."\r\n",
            'content'=> $query );

// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));

// Read page rendered as result of your POST request
$result =  file_get_contents (
              'http://localhost/receive.php',  // page url
              false,
              $context);

// Server response is now stored in $result variable so you can process it
echo($result);
?>

【讨论】:

    【解决方案2】:

    使用 PHP 发送 HTTP 请求是可能,但不是微不足道。看看 cURL,或者更好 - 像 Artax 这样的库。

    【讨论】:

      猜你喜欢
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 2010-12-12
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多