HttpRequest (PHP), how to post objects - php

code is as below:
<?php
//set up variables
$theData = '<?xml version="1.0"?>
<note>
<to>php.net</to>
<from>lymber</from>
<heading>php http request</heading>
<body>i love php!</body>
</note>';
$url = 'http://www.example.com/script.php';
//create the httprequest object
$httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options);
//add the content type
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
//add the raw post data
$httpRequest_OBJ->setRawPostData ($theData);
//send the http request
$result = $httpRequest_OBJ->send();
//print out the result
echo "<pre>"; print_r($result); echo "</pre>";
?>
Now httprequest calls the script here:
http://www.example.com/script.php
Over there I want to access the object, so that I can manipulate the data and send it back:
$httpRequest_OBJ->setRawPostData ($theData);
but it does not work. I tried $_POST['theData'], but this only works if you use $r->**addPostFields**(array('user' => 'mike', 'pass' => 's3c|r3t'));
How can I access the object $theData?
Thanks.

I think what you are after is php://input
So you can get the whole lot of XML that you posted like this:
$fp = fopen('php://input','r');
$data = '';
while (!feof($fp)) $data .= fread($fp,1024);
// $data should now contain the XML posted in your example
As a side note, I think the line
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
...should probably just read
$httpRequest_OBJ->setContentType = 'text/xml';

Related

Sending the form data from my website to a remote http server via php

hello all
i am receiving the http post request from html form to my action.php file and then this php file is writing these values into a text file.
now i want the php file to send the data it receives to a remote http server for further processing (i am using a simple python http server)
here is my php code :
<?php
$data1 = $_REQUEST['key1'];
$data2 = $_REQUEST['key2'];
$data3 = $_REQUEST['key3'];
$data4 = $_REQUEST['key4'];
$data5 = $_REQUEST['key5'];
$fp = fopen('datafile.txt', 'w+');
fwrite($fp, implode("\n", [$data1, $data2, $data3, $data4, $data5]));
fclose($fp);
// example data
$data = array(
'key1'=> $data1,
'key2'=> $data2,
'key3'=> $data3,
'key4'=> $data4,
'key5'=> $data5
);
// build post body
$body = http_build_query($data); // foo=bar&baz=boom
// options, headers and body for the request
$opts = array(
'http'=>array(
'method'=>"POST",
'header'=>"Accept-language: en\r\n",
'data' => $body
)
);
// create request context
$context = stream_context_create($opts);
// do request
$response = file_get_contents('http://2.22.212.12:42221', false, $context)
?>
but when i submit the form , only the datafile.txt file is generated and no post request is sent to the remote python server
what am i doing wrong ?
I would highly recommend using Guzzle, but the docs for stream_context_create use fopen() instead of file_get_contents(), so that might one factor.
Another is the header. The comments on the doc page set the header this way for POST requests:
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($body) . "\r\n",
Take a look at the answers here too for more examples.

Put JSON content in a JSON file

I'm trying to put a JSON response from an API connection into a JSON file but when I do so I only get the value true in the JSON File.
The API PHP function:
public function Get_Reviews(){
$token = 'CDF494791E05F36531FA0F5F';
$headers[] = 'Authorization: Bearer ' . $token;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => '[URL]',
CURLOPT_HTTPHEADER => $headers
));
$response = curl_exec($curl);
curl_close($curl);
return json_encode($response);
}
and the code to put the response in a JSON file:
$api = new Reviews();
$reviews = $api->Get_Reviews();
$file = "reviews_created.json";
unlink($file);
$fp = fopen($file, 'w');
fwrite($fp, $reviews);
fclose($fp)
When I var_dump($reviews) I get a clean JSON response and I can copy that manually in a JSON file but I need to make this dynamic.
I hope anyone can help me with this.
Check this sample code. It's working fine in my side.
<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "your API end point"
));
// Send the request & save response to $resp
$result = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
//header('Content-Type: application/json');
//echo $result;
$file = 'product.json';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= $result;
// Write the contents back to the file
file_put_contents($file, $current);
Note : Give destination JSON file as write permission.

error writing xml data from post request in PHP

im trying to simulate a webservice post request via my local machine using PHP, and im getting some problems.
First of all, I have a php file that is sending an xml file via Post, inside an array:
<?php
$xml = file_get_contents('localstorage.xml');
$url = 'http://127.0.0.1/projects/My_webservice/rebreFitxer1.php';
$post_data = array('xml' => $xml, );
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
?>
Then in the other side i have another php file that loads the xml content and writes it on a xml file.
<?php
header('Content-type: text/xml');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$postText = file_get_contents('php://input'); // load the content loaded via POST
$postText = utf8_encode($postText);
$datetime = date('ymdHis');
$xmlfile = "myfile" . $datetime . ".xml"; //new file name
$FileHandle = fopen($xmlfile, 'w') or die("can't open file");
// open the new file in writing mode
fwrite($FileHandle, $postText);
fclose($FileHandle);
?>
What i get from this is a bad formed xml wich i tried to convert encoding but nothing seems to operate.
Here's what i get:
xml=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22utf-8%22%3F%3E%0A%3CXml...........etc
---^
It seems that symbols "< >" are not well written--> Nom%3ERetard%3C%2FNom%3E%0A++++++%3C
but i dont know how to fix it
I'm new on php and im sure that there's something i've done bad...
Thanks in advance
Your XML should be stored in $_POST["xml"] variable. So you can try:
<?php
$postText = $_POST["xml"];
?>

Display XML as response in PHP with eBay API

Following tutorial shows how to display data as HTML based on that I just need to show response of XML as opposed to parsing it. I have tried to find solution but didn't have any luck. Any help will be appreciated.
<?php
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call
$query = 'iphone'; // Supply your own query keywords as needed
// Construct the findItemsByKeywords POST call
// Load the call and capture the response returned by the eBay API
// The constructCallAndGetResponse function is defined below
$resp = simplexml_load_string(constructPostCallAndGetResponse($endpoint, $query));
// Check to see if the call was successful, else print an error
if ($resp->ack == "Success") {
$results = ''; // Initialize the $results variable
// Parse the desired information from the response
foreach($resp->searchResult->item as $item) {
$link = $item->viewItemURL;
$title = $item->title;
// Build the desired HTML code for each searchResult.item node and append it to $results
$results .= "<tr><td><img src=\"$pic\"></td><td>$title</td></tr>";
}
}
else { // If the response does not indicate 'Success,' print an error
$results = "<h3>Oops! The request was not successful";
$results .= "AppID for the Production environment.</h3>";
}
function constructPostCallAndGetResponse($endpoint, $query) {
global $xmlrequest;
// Create the XML request to be POSTed
$xmlrequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xmlrequest .= "<findItemsByKeywordsRequest
xmlns=\"http://www.ebay.com/marketplace/search/v1/services\">\n";
$xmlrequest .= "<keywords>";
$xmlrequest .= $query;
$xmlrequest .= "</keywords>\n";
$xmlrequest .= "<paginationInput>\n
<entriesPerPage>3</entriesPerPage>\n</paginationInput>\n";
$xmlrequest .= "</findItemsByKeywordsRequest>";
// Set up the HTTP headers
$headers = array(
'X-EBAY-SOA-OPERATION-NAME: findItemsByKeywords',
'X-EBAY-SOA-SERVICE-VERSION: 1.3.0',
'X-EBAY-SOA-REQUEST-DATA-FORMAT: XML',
'X-EBAY-SOA-GLOBAL-ID: EBAY-GB',
'X-EBAY-SOA-SECURITY-APPNAME: ******',
'Content-Type: text/xml;charset=utf-8',
);
$session = curl_init($endpoint); // create a curl session
curl_setopt($session, CURLOPT_POST, true); // POST request type
curl_setopt($session, CURLOPT_HTTPHEADER, $headers); // set headers using $headers
array
curl_setopt($session, CURLOPT_POSTFIELDS, $xmlrequest); // set the body of the POST
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); //
$responsexml = curl_exec($session); // send the request
curl_close($session); // close the session
return $responsexml; // returns a string
} // End of constructPostCallAndGetResponse function
?>
Try changing this (wrapped for clarity):
$resp = simplexml_load_string(
constructPostCallAndGetResponse($endpoint, $query)
);
to this:
$xmlString = constructPostCallAndGetResponse($endpoint, $query);
$resp = simplexml_load_string($xmlString);
// Now you have your raw XML to play with
echo htmlentities($xmlString);
// The XML document $resp is available too, if you wish to do
// something with that
The original feeds the XML response immediately into an XML parser, and creates an XML object with it (look up SimpleXML in the PHP manual for details). Here, we've split the two calls up, so the XML string is now saved in an intermediate variable.

JSON full circle (PHP)

I've reduced to the simplest form, and am still stumbling...I've spent more than 30 hours researching and testing. According to all of the posts which never show more than 15° of the entire circle, this is supposed to be really easy.
I want to:
Send query parameters (in JSON) from an Android Phone to a WAMP server...This may be as much as a complete dump of a local SQLite table, so query strings just won't cut it.
Have the WAMP server read the JSON data, formulate a SQL query and submit to the mySQL database
Package a response as JSON data (from a simple "OK" to a full table dump)
Return the response package to the Android phone
This is already a fully functional WAMP application, and I want to integrate Android access. For this reason, I really want to avoid AJAX, since I want to maintain consistency with what's already in place.
I've reduced this to the simplest loop and am hitting snags. I'm using send.php to post some JSON data to receive.php. At this point, I just need receive.php to read the data and send it back (slightly modified) to send.php
send.php is properly reading stock JSON sent from receive.php. I just can't get any sign of life that receive.php even recognizes the JSON sent to it.
PLEASE don't direct me towards cURL...from everything I've found regarding Android and JSON, cURL is a tangent which will send me full circle back into nonfunctionality.
APACHE 2.2.22, PHP 5.4.3
Like I said, I've reduced this to the simplest form to demonstrate a full circle...
send.php:
<?php
$url = "http://192.168.0.102:808/networks/json/receive.php";
$data = array(
'param1' => '12345',
'param2' => 'fghij'
);
$json_data = json_encode($data);
$options = array(
'http' => array(
'method' => 'POST',
'content' => $json_data,
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n" .
'Content-Length: ' . strlen($json_data) . "\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result , true);
echo '[' . $response['param1'] . "]\n<br>";
//THIS WORKS! send.php displays "Initialized"
?>
receive.php
<?php
$newparam = 'Initialized';
//HERE I NEED TO read the JSON data and do something
$data = array(
'param1' => $newparam,
'param2' => 'pqrst'
);
header('Content-type: application/json');
echo json_encode($data);
?>
It is actually easy, as stated in all the incomplete explanations...I got the full circle to work finally
I've chosen simplicity to prove I could travel full circle, and I have now done so.
send.php
<?php
//The URL of the page that will:
// 1. Receive the incoming data
// 2. Decode the data and do something with it
// 3. Package the results into JSON
// 4. Return the JSON to the originator
$url = "http://192.168.0.102:808/networks/json/receive.php";
//The JSON data to send to the page (above)
$data = array(
'param1' => 'abcde',
'param2' => 'fghij'
);
$json_data = json_encode($data);
//Prep the request to send to the web site
$options = array(
'http' => array(
'method' => 'POST',
'content' => $json_data,
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
//Make the request and grab the results
$result = file_get_contents( $url, false, $context );
//Decode the results
$response = json_decode( $result , true);
//Do something with the results
echo '[' . $response['param1'] . "]\n<br>";
?>
receive.php
<?php
//K.I.S.S. - Retrieve the incoming JSON data, decode it and send one value
//back to send.php
//Grab the incoming JSON data (want error correction)
//THIS IS THE PART I WAS MISSING
$data_from_send_php = file_get_contents('php://input');
//Decode the JSON data
$json_data = json_decode($data_from_send_php, true);
//CAN DO: read querystrings (can be used for user auth, specifying the
//requestor's intents, etc)
//Retrieve a nugget from the JSON so it can be sent back to send.php
$newparam = $json_data["param2"];
//Prep the JSON to send back
$data = array(
'param1' => $newparam,
'param2' => 'pqrst'
);
//Tell send.php what kind of data it is receiving
header('Content-type: application/json');
//Give send.php the JSON data
echo json_encode($data);
?>
AND Android integration...called with a Button.onClickListener
public void getServerData() throws JSONException, ClientProtocolException, IOException {
//Not critical, but part of my need...Preferences store the pieces to manage JSON
//connections
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String netURL = prefs.getString("NetworkURL", "");
// "http://192.168.0.102:808/networks/json"
String dataPage = prefs.getString("DataPage", "");
// "/receive.php"
//NEEDED - the URL to send to/receive from...
String theURL = new String(netURL + dataPage);
//Create JSON data to send to the server
JSONObject json = new JSONObject();
json.put("param1",Settings.System.getString(getContentResolver(),Settings.System.ANDROID_ID));
json.put("param2","Android Data");
//Prepare to commnucate with the server
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost(theURL);
//Attach the JSON Data
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
//Send and Receive
String response = httpClient.execute(postMethod,resonseHandler);
//Begin reading and working with the returned data
JSONObject obj = new JSONObject(response);
TextView tv_param1 = (TextView) findViewById(R.id.tv_json_1);
tv_param1.setText(obj.getString("param1"));
TextView tv_param2 = (TextView) findViewById(R.id.tv_json_2);
tv_param2.setText(obj.getString("param2"));
}

Categories