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.
Related
While using something like this
"
Dictionary<string, string> form = new Dictionary<string, string>
{
{_metajson, JsonConvert.SerializeObject(metaJson)}
};
HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(form));
However on the php side of things with $_Request I get the string and all the quotes are turned into " so the json looks like
{"name":"myname"}
Is there a better way to send json to a php backend?
On the PHP end of things I am simply assigning the json which has now lost the quotes and has weird marks with
$json = $_REQUEST["test"];
The json I am sending is in memory, its not saved to a file anywhere. It is very small like shown above and is needed for the purposes of the application I am writing.
Use php://input
php://input is a read-only stream that allows you to read raw data from the request body.
Example:
$json_string = file_get_contents('php://input');
//Converting It to PHP object:
$data = json_decode($json_string );
I was just working with the same problem and here is my solution, it works for me
$data = $_POST['json'] ;
$json = json_decode($data, true);
echo json_encode($json);
afterwards, you can take the $json variable an do whatever you want to do with it
I ended up changing the approach which worked very well
I simply base64 encoded the json to avoid http changing special characters to odd string formats like " to " and what not.
C# side - using this string in the dictionary form
string encodedJson = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(metaJson)));
PHP side
$encoded_input = $_REQUEST["metajson"];
$base64_decoded_input = base64_decode($encoded_input, true);
if (!$base64_decoded_input)
{
// error out
}
$meta_json = json_encode(json_decode($base64_decoded_input));
I have the following PHPcode:
include 'db.php';
$user = $_POST['username'];
$q = $connection->query('SELECT id FROM myTable WHERE username=".$user."');
foreach($q AS $row) {
echo $row['id'];
}
I'm trying to make a C# application post a variable to a PHP page that then queries the db and echos a string that will be used in the C# app. My C# code looks like this:
public string getId(string url)
{
string test = "testing123";
NameValueCollection formData = new NameValueCollection();
formData["username"] = test;
using (WebClient wc = new WebClient())
{
byte[] resp = wc.UploadValues(url, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(resp);
wc.Dispose();
Console.WriteLine(responsefromserver);
return responsefromserver;
}
}
As you can see, I just want to write what the app gets back from the PHP page to the console and then return it, but when I run the app, it returns nothing. At least it appears to. Does anyone have any idea why? Sorry if this is blatantly obvious, I'm still pretty new to the whole C# thing.
replace
$q = $connection->query('SELECT id FROM myTable WHERE username=".$user."');
with
$q = $connection->query('SELECT id FROM myTable WHERE username='.$user.';');
and try again.
As a best practise, use prepared statement to avoid SQL injection.
I want to post variables from C# to a php-script on my webserver. I tried this following code from the internet but it returns this error message:
Error: The remote server returned an error. (406) Not Acceptable.
The c# part:
string URI = "https://myserver.com/post.php";
string myParameters = "param1=value1¶m2=value2";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
MessageBox.Show(HtmlResult);
}
The php part:
<?php
if(isset($_POST['param1']) && isset($_POST['param2']))
{
$user = $_POST['param1'];
$date = $_POST['param2'];
echo $user . ' : ' . $date;
}
?>
I have tested it with a test post server and it works but it won't work on my server.
Your backend service is saying that the response type it is returning is not provided in the Accept HTTP header in your Client request.
Source: What is "406-Not Acceptable Response" in HTTP?
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/
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