php - 使用 file_get_content 发布数据

标签 php http post

我对如何在帖子中使用 file_get_content 做了一些研究。我也读过this one老实说,我不明白,因为我对 PHP 不太熟悉。下面是我的 php 代码,用于获取我的 json 并将其用于我的 ajax 请求,使用 methog GET.:

<?php 
    echo(file_get_contents("http://localhost:8001/" . $_GET["path"] . "?json=" . urlencode($_GET["json"])));
?>

现在,我正在使用 POST 方法,但我不知道如何修改我的 php 代码以从我的 javascript 发布我的数据。下面是我想在我的 url 请求中发布的 data(这也是我在 GET 方法中用作 json 的内容):

{"SessionID":"9SQLF17XcFu0MTdj5n",
  "operation":"add",
  "transaction_date":"2011-7-28T00:00:00",
  "supplier_id":"10000000108",
  "wood_specie_id":"1",
  "lines":  [{"...":"...","..":"..."},{"...":"...","..":"..."}],
  "scaled_by":"SCALED BY",
  "tallied_by":"TALLIED BY",
  "checked_by":"CHECKED BY",
  "total_bdft":"23.33",
  "final":"N"}

我只需要更改这段代码

echo(file_get_contents("http://localhost:8001/" . $_GET["path"] . "?json=" . urlencode($_GET["json"])));

使用 POST 发送我的帖子我的数据。

编辑: 我需要产生这样的请求:

http://localhost/jQueryStudy/RamagalHTML/processjson.php?path=getData/supplier?​json={"SessionID":"KozebJ4SFqdqsJtRpG6t1o3uQxgoeLjT"%2C"dataType":"data"}

最佳答案

您可以将流上下文作为第三个参数传递给 file_get_contents。使用 Stream Context,您可以影响 HTTP 请求的发出方式,例如您可以更改方法、添加内容或任意标题。

file_get_contents($url, false, stream_context_create(
    array (
        'http' => array(
            'method'=>'POST',
            'header' => "Connection: close\r\nContent-Length: $data_len\r\n",
            'content'=>$data_url
        )
    )
));

每次请求后,PHP 将自动填充 $http_response_header,其中包含有关请求的所有信息,例如状态代码和其他东西。

$data_url = http_build_query (array('json' => $_GET["json"]));
$data_len = strlen ($data_url); 

echo file_get_contents("http://localhost:8001/" . $_GET["path"], false, stream_context_create(
    array (
        'http' => array(
            'method'=>'POST',
            'header' => "Connection: close\r\nContent-Length: $data_len\r\n",
            'content'=>$data_url
        )
    )
));

关于php - 使用 file_get_content 发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6854526/

相关文章:

php - magento 前端突然 503 - 如何调试

http - websocket 如何知道服务器已关闭?

php - 使用 HttpURLConnection 时,mysql 上的 $_POST 为空

c# - 使用 HttpWebRequest 发布表单数据

php - 所有类函数中的全局变量

php - 使用 php-jquery 替换图像时出现问题

python - 在 Python CGI 中返回 http 状态代码

objective-c - iOS http post 对 NSDictionary 或 NSArray 的响应

php - mysql 连接两个表

security - 安全 token URL - 它有多安全?代理身份验证作为替代方案?