使用file_get_content发布数据 [英] post data with file_get_content

查看:138
本文介绍了使用file_get_content发布数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经就如何使用 file_get_content 进行了一些研究。我还阅读了这一个我老实说不明白,因为我不熟悉PHP。下面是我的PHP代码获取我的json并将其用于我的ajax请求,使用methog GET 。:

I have done some research regarding on how to use file_get_content with post. And I have also read this one which is I honestly don't understand since I am not that familiar with PHP. Below is my php code in getting my json and used it for my ajax request, using methog GET.:

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

现在,我使用方法 POST 和我不知道如何修改我的PHP代码从我的JavaScript发布我的数据。下面是我想要在我的网址请求中发布的数据(这也是我在方法中用作 json 的方法 GET ):

Now, I am using method POST and I dont know how to modify my php code to post my data from my javascript. Below is my data which I wanted to post in my url request (that is also what I used as json in method GET):

{"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 发送我的数据我的数据。

with POST to send my post my data.

编辑:
我需要提出这样的请求:

I need to produce a request like this:

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


推荐答案

您可以传递流上下文作为 file_get_contents 的第三个参数。使用流上下文,您可以影响HTTP请求的生成方式,例如您可以更改方法,添加内容或arbirtrary标题。

You can pass a Stream Context as the third argument to file_get_contents. With the Stream Context, you can influence how the HTTP request will be made, e.g. you can change the Method, add Content or arbirtrary headers.

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 ,其中包含有关请求的所有信息,例如状态代码和东西。

After each request, PHP will automatically populate the $http_response_header which will contain all the information about the request, e.g. Status Code and stuff.

$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
        )
    )
));

这篇关于使用file_get_content发布数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆