Equivalent of function UploadData for PHP - c#

I have the following script in C# to upload some XML to a Server
using (System.Net.WebClient myWebClient = new System.Net.WebClient())
{
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// Post and return Xml
byte[] bytes = myWebClient.UploadData(url, "POST", System.Text.Encoding.ASCII.GetBytes(Xml_to_Send));
Xml_Returned = System.Text.Encoding.ASCII.GetString(bytes);
bytes = null;
}
But i need some equivalente that do the same for PHP.
What function should i use to simule somthing like that ?

You can use the PHP CURL library to upload files that way. Check this guide:
http://blogs.digitss.com/php/curl-php/posting-or-uploading-files-using-curl-with-php/

Related

How do I upload document by converting HttpClient request to RestSharp request?

After i logged in to API i used, I am trying to upload a document with using RestSharp.
I was able to do this using Postman. Screenshot is given below:
Postman code generator generates this code block for me:
var client = new RestClient("http://80.211.238.187/AcumaticaERP/entity/Default/17.200.001/StockItem/POSTMAN123/files/sample.pdf");
client.Timeout = -1;
var request = new RestRequest(Method.PUT);
request.AddHeader("Content-Type", "application/pdf");
request.AddParameter("application/pdf", "<file contents here>", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
but idk how to edit the <file contents here> part from given code block above.
I was also able to achieve it using the HttpClient suggested in the respective API's documentation guide:
using (StreamReader sr = new StreamReader(#"C:\Users\fcomak\Downloads\sample.pdf"))
{
_httpClient.PutAsync("http://80.211.238.187/AcumaticaERP/entity/Default/17.200.001/StockItem/POSTMAN123/files/sample.pdf", new StreamContent(sr.BaseStream))
.Result
.EnsureSuccessStatusCode();
}
But i need to convert HttpClient request to RestSharp request. I tried to achieve this using RestSharp, but failed. Even if I could send the file, its content was not browse correctly. Here is the code block i tried:
using (StreamReader sr = new StreamReader(#"C:\Users\fcomak\Downloads\sample.pdf"))
{
restClient.Execute(new RestRequest("http://80.211.238.187/AcumaticaERP/entity/Default/17.200.001/StockItem/POSTMAN123/files/sample.pdf", Method.PUT)
.AddHeader("Content-Type", "application/pdf")
.AddParameter("application/pdf", new StreamContent(sr.BaseStream), ParameterType.RequestBody));
}
I can sending or getting json contents by using this api with this restClient by the way. And of course i logged in already. The reason for my failure is about my restClient.
I would be grateful for any help.
I just solved the problem.
using (WebClient wc = new WebClient())
{
byte[] value = wc.DownloadData("http://www.africau.edu/images/default/sample.pdf");
restClient.Execute(new RestRequest("http://80.211.238.187/AcumaticaERP/entity/Default/17.200.001/StockItem/POSTMAN123/files/sample.pdf", Method.PUT)
.AddHeader("Content-Type", "application/pdf")
.AddParameter("application/pdf", value, ParameterType.RequestBody)
);
}
As you see, i used WebClient.DownloadData() instead of StreamReader.BaseStream()
Or, you can convert you local data to byte array with File.ReadAllBytes()
string entitySource = #"C:\Users\fcomak\Downloads\sample2.pdf";
byte[] value = File.ReadAllBytes(entitySource);
restClient.Execute(new RestRequest(entityBasePath + entityName + "/" + inventoryID + "/files/" + fileName, Method.PUT)
.AddHeader("Content-Type", "application/pdf")
.AddParameter("application/pdf", value, ParameterType.RequestBody)
);
FYI

Post data to php

I ran into a problem lately:
C# code:
string URI = "http://cannonrush.tk/UpdateLogFile.php";
string myParameters = "text=test123";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
Console.WriteLine(HtmlResult);
}
PHP file:
<?php
if (isset($_GET['text'])) {
$file = "LogFile.txt";
$handle = fopen($file, 'a') or die('ERROR: Cannot write to file: ' . $file);
date_default_timezone_set('Europe/Amsterdam');
$data = '~ ' . date('l jS \of F Y h:i:s A') . '>> ' . $_GET['text'] . "\n\n";
fwrite($handle, $data);
fclose($handle);
echo "SUCCESS";
} else {
echo "ERROR: Access forbidden without text";
}
?>
Now, whenever I run the above C# code, I get this output printed:
ERROR: Access forbidden without text
I have tried numerous versions to post data from C# to php, but nothing seems to work.
Any ideas?
Change $_GET["text"] to $_POST["text"] in the php file, or use DownloadString() instead of UploadString() in your C# code.
$_GET is only populated in GET requests, so UploadString will not work:
Uploads the specified string to the specified resource, using the POST method.
If you want to allow either verb, use $_REQUEST instead.

How to handle C# .NET POST and GET commands

The current project I am working on requires a 2 way communication from the bot to my website.
Supposing the example URL is www.example.com/foobar.php or something, can you explain me how to POST and GET data from there?
Thanks a lot.
P.S. - Using webclient right?
I'd suggest using RestSharp. It's a lot easier than using WebClient, and gives you a lot more options:
var client = new RestClient("http://www.example.com/");
//to POST data:
var postRequest = new RestRequest("foo.php", Method.POST);
postRequest.AddParameter("name", "value");
var postResponse = client.Execute(postRequest);
//postResponse.Content will contain the raw response from the server
//To GET data
var getRequest = new RestRequest("foo.php", Method.GET);
getRequest.AddParameter("name", "value");
var getResponse = client.Execute(getRequest);
Yes, you can use WebClient:
using (WebClient client = new WebClient())
{
NameValueCollection nvc = new NameValueCollection()
{
{ "foo", "bar"}
};
byte[] responseBytes = client.UploadValues("http://www.example.com/foobar.php", nvc);
string response = System.Text.Encoding.ASCII.GetString(responseBytes);
}
You can use WebClient
Look up method UploadString and DownloadString

C# file uploading with a string using on PHP server

I am uploading a file with C# code on php server. But facing some issues.
First I was using a WebClient Object to upload file by calling UploadFile() method, and uploading string to by calling UploadString() method by following code:
String StoreID = "First Store";
WebClient Client = new WebClient();
String s = Client.UploadString("http://localhost/upload.php", "POST", StoreID);
Client.Headers.Add("Content-Type","binary/octet-stream");
byte[] result = Client.UploadFile("http://localhost/upload.php", "POST", "C:\\aaaa.jpg");
s = s + System.Text.Encoding.UTF8.GetString(result,0,result.Length);
Issue is that I am requesting two times so string and file is not being send at same time. I am receiving either String or File. But I need both at same time. I don't want to use UploadData() becuase it will use byte codes and I have know I idea how to extract it in php.
Let that string is folder name, i have to send string and file, so that file could save at specified folder at php server.
I studied there may be a solution with WebRequest and WebResponse object. But dont know how to send request using WebResponse by C# and get it at PHP.
Any Suggestions!!!!
Try this :
WebClient web = new WebClient();
try{
web.UploadFile("http://" + ip + "/test.php", StoreID);
}
catch(Exception e)
{
MessageBox.Show("Upload failed");
}
Now you can access the file from the PHP file.
<?php
//check whether the folder the exists
if(!(file_exists('C:/Users/dhanu-sdu/Desktop/test')))
{
//create the folder
mkdir('C:/Users/ComputerName/Desktop/test');
//give permission to the folder
chmod('C:/Users/ComputerName/Desktop/test', 0777);
}
//check whether the file exists
if (file_exists('C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
//move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]);
}
?>
Also, you can download data from a PHP server and display it in a C# web browser by using the following codes :
WebClient web = new WebClient();
try{
byte[] response = web.DownloadData("http://" + ip +"/test.php");
webBrowser1.DocumentText = System.Text.ASCIIEncoding.ASCII.GetString(response);
}
catch(Exception e)
{
MessageBox.Show("Download failed");
}
You can create a webservice with php that accepts a file. Then publish that webservice, and add it to you c# references, then just call teh method from within your c# code that accepts the file, and vualá!
How to create SOAP with php link

PHP equivalent of this .net/C# code on async HttpWebRequest, custom headers binary payload and analyzing responses

I am looking for PHP equivalent of the below code even if it is not a compilable code just providing the high level functions to use to perform each of these functionality would be great.
string subscriptionUri = "sample.com";
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
sendNotificationRequest.Method = "POST";
sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.ContentLength = notificationMessage.Length;
byte[] notificationMessage = new byte[] {<payload>};
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Sends the notification and gets the response.
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
So basically I am looking for PHP equivalent of the following
Send an Async request with some custom headers and content type and send it async/stream
create a payload in byte from the string
get the response and look at the headers.
There's some function here I think that it will answer your question
CURL: http://php.net/manual/en/book.curl.php
FSOCKOPEN: http://php.net/manual/en/function.fsockopen.php
file_get_contents: http://php.net/manual/en/function.file-get-contents.php
get header: http://php.net/manual/en/function.get-headers.php
The way to do it is using curl http://php.net/manual/en/book.curl.php with the settings:
CURLOPT_WRITEFUNCTION
CURLOPT_HEADERFUNCTION
I think that they allow async comm by using callback function. not 100% sure.
http://www.php.net/manual/en/function.curl-setopt.php

Categories

Resources