error writing xml data from post request in PHP - 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"];
?>

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.

PHP Posting data to another php file hosted in a remote server using file_get_contents

I have access to 3 different remote servers. They all host the same php file, it's named processing.php.
And in a different server I have 3 pages :
index.html : that contains a form with POST method that send data to forward.php
forward.php : that forward the form values to processing.php on the other servers
processing.php : Display the posted data
The Problem : the code in processing.php is not executed and the returned result is a plain text of the source code of processing.php!!
forward.php :
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
rtrim($_POST['listserver'],"-");
$listServer = explode("-",$_POST['listserver']);
foreach ($listServer as $server){
if(!empty($server)){
$url = 'http://'.$server.'/processing.php';
$data = array('field1' => $field1, 'field2' => $field2);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo "You can't ";
}else{
echo ('result : '.$result);
}
}
}
Processing.php
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$result = $field1+$field2;
$myFile = "files/result.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $result);
fclose($fh);
But in all the servers, result.txt is empty!!
Thanx to #MarkusZeller suggestion, I managed to get it work using cURL.
This thread was very helpful, thank you Stack Over Flow community !

PHP GeoServer Proxy Shape/Zip Request Returns Text

The Problem
Our GeoServer access is being proxied by a PHP script that handles the authorization/authentication. This works fine for WMS/WFS requests within an OpenLayers map, but not so much when trying to download a zipped-up shapefile the same way: the response ALWAYS returns the request as text.
I know that my URL is correct, because when I take the prepped GeoServer URL and enter credentials manually, I get the desired "Save As" popup:
When running it through the proxy, however, I get no dialog and a bunch of garbage:
The Solution Attempts
Most suggestions I've found point to:
stream_context_create
Setting Content-Disposition in the header
readfile
The Code
URL Prep
Not sure if it matters, but here is how I am preparing the URL to send to GS (and that URL works fine sans proxy, manual credentials):
// Encode geoserver credentials
$auth = base64_encode('username:password');
// Base URL and parameters
$url = 'https://example.com/mygeoserverpath/wfs?';
$query = '';
// Extract arguments
$orig_proxy_url = $_SERVER['REQUEST_URI'];
$orig_query = parse_url($orig_proxy_url, PHP_URL_QUERY);
parse_str($orig_query, $orig_args);
// Loop over arguments, append to base url
foreach ($orig_args as $key => $value) {
if ($key === 'cql_filter') {
$value = rawurlencode($value);
}
$query = $query . '&' . $key . '=' . $value;
}
$url = $url . $query;
Using stream_context_create with Other Stuff
$opts = array(
'http' => array (
'method' => "GET",
'header' => "Authorization: Basic $auth"
. "Content-Description: File Transfer\r\n"
. "Content-Type: application/zip\r\n"
. "Content-disposition: attachment; filename=testing.zip\r\n"
));
$ctx = stream_context_create($opts);
...in conjunction with some other attempts:
// file_get_contents returns text
$output = file_get_contents($url,false,$ctx);
// readfile returns text
readfile($url,false,$ctx);
// fopen/passthru returns text
$fp = fopen($url,'r',0,$ctx);
fpassthru($fp);
exit;
Setting Headers Directly
I could get the Save dialog to appear this way, but it always was an empty zip.
header("Content-Description: File Transfer");
header("Content-Type: application/zip");
header("Content-disposition: attachment; filename=testing.zip");
header("Authorization: Basic $auth");
cURL
Not much to comment on here as I've been saving it as a very last resort.
Now What?
It shouldn't be this difficult considering GS does 99% of the work creating the zipped-up shapefile, but I'm running out of things to try. Any suggestions would be appreciated!
Sounded like this worked:
$opts = array(
'http' => array (
'method' => "GET",
'header' => "Authorization: Basic $auth"
));
header("Content-Disposition: attachment; filename=testing.zip");
$ctx = stream_context_create($opts);
$fp = fopen($url,'r',0,$ctx);
fpassthru($fp);

Why I am getting corrupted files by downloading it via file_get_contents?

$source_path = 'https://bip.wzp.pl/attachments/' . $filename;
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content-type: application/pdf",
)
);
$context = stream_context_create($opts);
$data = file_get_contents($source_path, false, $context);
if(($handle = fopen($dest_path, "w"))) {
fwrite($handle, $data);
fclose($handle);
return $filename_converted;
}
$source_path is e.g:
https://bip.wzp.pl/attachments/28172_Statut Województwa
Zachodniopomorskiego.pdf
When I trying it browser, a pdf document displayes properly.
But downloaded file via PHP, it is always corrupted.
EDIT
I checked $data content. It has front page html :/
It strange putting $source_path to browser returns pdf
Seems like you try to download a PDF, try saving it as a binary file using:
fopen($dest_path, "wb")

HttpRequest (PHP), how to post objects

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

Categories