3

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"])));
?>

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"}

I just need to change this code

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

with POST to send my post my data.

EDIT: I need to produce a request like this:

http://localhost/jQueryStudy/RamagalHTML/processjson.php?path=getData/supplier?​json={"SessionID":"KozebJ4SFqdqsJtRpG6t1o3uQxgoeLjT"%2C"dataType":"data"}
Community
  • 1
  • 1
jayAnn
  • 827
  • 3
  • 18
  • 38
  • you need to use curl or sockets for this. – Ilia Choly Jul 28 '11 at 05:41
  • I am reading about it right now and I am striving hard to understand it... oh, PHP – jayAnn Jul 28 '11 at 05:49
  • do `echo http_build_query (array('json' => $_GET["json"]));` and show it to us – SMka Jul 28 '11 at 08:29
  • and you wrote `I need to produce a request like this` - this is not a POST – SMka Jul 28 '11 at 08:40
  • just use `$_REQUEST` in `processjson.php`. `echo $_REQUEST['SessionID']`; what you see? – SMka Jul 28 '11 at 08:43
  • if you want `processjson.php` return response in json - smthing like this `$retval = array('error' => array('msg'=>'aaaaaa')); echo json_encode($retval); die;` should be used – SMka Jul 28 '11 at 08:50
  • i did something like this `$retval = array('error' => array('msg'=>http_build_query (array('json' => $_GET["json"])))); echo json_encode($retval); die;` and it return `{"error":{"msg":""}` – jayAnn Jul 28 '11 at 08:57
  • THEHE ARE NO $_GET; and jquery is smart enough. replace `$_GET['json']` with `$_REQUEST['operation']` – SMka Jul 28 '11 at 09:01
  • But hey, It displays my Session id using your `$_REQUEST['SessionID']` with the `retval`. :) – jayAnn Jul 28 '11 at 09:04
  • wow :) if you want send ALL your data back with error, just repack request. `$retval = array('error' => array('msg'=> $_REQUEST)); echo json_encode($retval); die;` question answered? :) accept it :) – SMka Jul 28 '11 at 09:30
  • I tried it already now. Please see my edit. If you notice, there's an error `{"error":{"msg":"Server Error: Session has expired or does not exist.","class":"ESessionExpiredException"}}`, before the `retval` echo. It only means that the request does not go to my web service or there is no data being sent to my webservice. :( – jayAnn Jul 28 '11 at 10:00
  • this is not php nor jquery error. `ESessionExpiredException`. relogin to your remote service or send right token or 1001 reason more. i know nothing about remote service. – SMka Jul 28 '11 at 10:09
  • That error is from my webservice. It says expired or does not exist, meaning, the sessionID was expired or my webservice does not read it from my php/javascript. And it really dont get to my webservice. My data was not sent to my ajax call. And I know that its my php that has a problem. – jayAnn Jul 28 '11 at 10:14
  • I only have hard time sending request to my webservice with this one only since this is the only one where i used method `POST` while the other is `GET`. – jayAnn Jul 28 '11 at 10:16
  • and if you notice the url above, it only end in `tallyHdr`. That only means that the data was not really sent to my http request, compare the others above it.... – jayAnn Jul 28 '11 at 10:21
  • stop. stepbystep. 1. your jqury sends jsondata to process.php 2. from process.php you wanna do POST call to other service with data that jquery sends in step1?? 3. return result from external service to cally script (s1). right? – SMka Jul 28 '11 at 10:22
  • you blown my brain :)))) it will be much more faster for me to write all code myself :)))) and then email it to u as example :))))) zip your folder, mail me :)))) – SMka Jul 28 '11 at 10:23
  • it's ok, I might blow my head later. your code below only giveme this url `http://localhost/jQueryStudy/RamagalHTML/processjson2.php?path=update%2FtallyHdr`. It does not have the other data the i `POST`, `?​json={"SessionID":"KozebJ4SFqdqsJtRpG6t1o3uQxgoeLjT"%2C"data.....` – jayAnn Jul 28 '11 at 10:28
  • 1. how many times i wrote `replace $_GET with $_REQUEST`? FORGET _GET and _POST. USE $_REQUEST. you need more base knowlege of php & javascript to use different req types such as get or post. 2. `?​json=` replace with `&json=` because `?` sign already used before – SMka Jul 28 '11 at 10:36
  • http_build_query (array('json' => $_REQUEST)); – SMka Jul 28 '11 at 10:44
  • SMka, could you please update your answer.. Please... :) – jayAnn Jul 28 '11 at 11:40

3 Answers3

3

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

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
        )
    )
));
SMka
  • 3,021
  • 18
  • 14
  • I would **not** suggest rolling your own POST-request with raw headers etc. Down that path lies madness. If not for you, then for whoever has to maintain all the reinvented wheels later. – Darien Jul 28 '11 at 05:49
  • 1
    @Darien there is no reinventing of wheels here. Smka is just supplying Stream Context options for the Stream Wrapper. That is perfectly fine and much less cruft than using cumbersome cURL. – Gordon Jul 28 '11 at 07:08
  • so how can i use it with my code? I saw stream_context_create before while I am searching for some tips in the net, but I just don't understand how to use it – jayAnn Jul 28 '11 at 07:56
  • it still didnt post my data to my url :( – jayAnn Jul 28 '11 at 08:24
  • I've got this error `Content-type not specified assuming application/x-www-form-urlencoded` after I change my `$_GET` to $_REQUEST – jayAnn Jul 28 '11 at 12:24
1

What you need is cURL.

Example:

$dataString = "firstName=John&lastname=Smith";

$ch = curl_init();

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,2); // number of variables
curl_setopt($ch,CURLOPT_POSTFIELDS,$dataString);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • what is `$ch = curl_init();` for? How can I put my data from javascript in that `$dataString`? Is this all one php file? – jayAnn Jul 28 '11 at 05:52
  • I was thinking on using `http_build_query`. But I just don't know how to use it with my data or how can I pass my data to that `http_build_query`. – jayAnn Jul 28 '11 at 06:07
  • file_get_contents can do everything cURL can via stream wrappers. – Gordon Jul 28 '11 at 07:02
  • @Gordon, Please show me a good sample code that I can use. I am now having a headache studying about cUrl :( – jayAnn Jul 28 '11 at 07:40
0

If i understand you correctly(I might not) you should use CURL.
CURL is the way to submit POST requests within PHP. (but it is not the only way) What you are doing is sending the data by the GET method

some think like this, please read about it, this one will not work out of the box

<?php
 $ch = curl_init("http://localhost:8001/" . $_GET["path"] );
 curl_setopt ($ch, CURLOPT_POST, 1);
 curl_setopt ($ch, CURLOPT_POSTFIELDS, "json=".urlencode($_GET["json"]));
 curl_exec ($ch);
 curl_close ($ch);
?>
fatnjazzy
  • 6,070
  • 12
  • 57
  • 83
  • I send data using get before, but I now change it to `POST`. – jayAnn Jul 28 '11 at 05:49
  • so? Use CURL, that is the best way for this simple situation – fatnjazzy Jul 28 '11 at 05:54
  • If I use cUrl, how will I get my url and the path and data to be posted.? – jayAnn Jul 28 '11 at 06:02
  • I see that my program already read it my method as `POST`, but still my data was not being send. But that was great, (since my last php never read my data as post method). Now i only have to focus on how to pass my data. maybe `http_build_query` will do. – jayAnn Jul 28 '11 at 06:21
  • @jay `http_build_query` will only assemble the Query String for the URL, e.g. for the GET params. POST data is send via the POST body in the header. – Gordon Jul 28 '11 at 07:33
  • So how can I do it.? Using the code above, I cannot pass my data. – jayAnn Jul 28 '11 at 07:49