send C# string to .PHP page - c#

After looking a bit around I came to this page. Here, I found some code to send a C# string to a PHP page.
However, after implementing it in my own program it did not work. Here is my code:
private void executesend()
{
using (WebClient client = new WebClient())
{
client.UploadString(url,"POST",keys);
}
}
For the PHP part, I have:
<?php
mysql_connect("localhost", "", "") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("dimittv89_dayz") or die(mysql_error()); // Select registration database.
$name = $_GET["message"];
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
$name = file_get_contents('php://input');
$opdracht = "INSERT INTO 'keys', (`key`) VALUES ('$name')";
print $name;
}
if (mysql_query($opdracht)){
echo "succesfully registerd to the melloniax u wil now be returned to our main page";
}
else{
echo "hey something went wrong there ! please try again in a minute";
}
?>
In the same topic one of the users also said to try this:
php?fmessage=testtesttest"
and write down the output using
$name = $_GET["message"];
print $name;
This did not work either. Am I doing something wrong?
Thanks for the help already
Well sofar i found out its not the send value thats wrong but the get value :
Username = Registry.CurrentUser.OpenSubKey("Username", true);
Name = "" + Username.GetValue("Uid");
in the regedit menu it says that the value is a REG_BINARY, are these readable with getvalue ?

use this code for c# and php :
private void executesend()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "message="+keys;
byte[] postBytes = Encoding.ASCII.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
}
catch (WebException)
{
MessageBox.Show("Please Check Your Internet Connection");
}
}
and php
<?php
mysql_connect("localhost", "", "") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("dimittv89_dayz") or die(mysql_error()); // Select registration database.
if (isset($_POST['message']))
{
$name = $_POST['message'];
$opdracht = "INSERT INTO keys (key) VALUES ('$name')";
print $name;
if (mysql_query($opdracht)){
echo "succesfully registerd to the melloniax u wil now be returned to our main page";
}
else{
echo "hey something went wrong there ! please try`enter code here` again in a minute";
}
}
?>

Related

C# python http post to C# httpwebrequest

i try to figure it out the black box of the server side that code by python for sending http post. In C# i trying to use httpwebrequest and httpwebresponse to send and receive message back from the server side.
Below is the python code:
**# Request login to server**
import httplib, urllib, requests
import sys, time
from requests.adapters import HTTPAdapter
import select, socket
s = requests.Session()
url = 'http://192.168.1.1/request_login'
data = 'user.login(test,test)' #login account and password set here
r = s.post(url, data=data)
if r.status_code != 200:
print "Failed loging in (%d)" % (r.status_code)
sys.exit(-1)
**# send key file to server**
url = 'http://192.168.1.1/request_sendfile'
files = {'file': (data_xml, open(data_xml, 'rb'), 'application/x-binary', {'Expires': '0'})} # **Don't understand this format**
r = s.post(url, files=files, timeout=30.0)
if r.status_code != 200:
print "Failed sending data file (%d, %s)" % (r.status_code, r.reason)
url = 'http://192.168.1.1/request_sendfile'
data = 'reader.view_log(4)'
r = s.post(url, data=data)
if r.status_code != 200:
print "Failed loging in (%d)" % (r.status_code)
sys.exit(-3)
print "Logs: "
print r.content
sys.exit(-4)
Above is the code for login and sending file to server in one session, i try to use C# do the same way.
I set two http request at the same time, however for the login is success while try to get second http request i get an error of "400" doesn't understand context of verb.
Below is the C# code:
private void httpost()
{
try
{
string Url = "http://192.168.1.1/request_login";
string Urls = "http://192.168.1.1/request_sendfile";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
HttpWebRequest requests = HttpWebRequest.Create(Urls) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "login";
string param = "user.login(test,test)";
byte[] bs = Encoding.ASCII.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
StreamReader sr = new StreamReader(response.GetResponseStream());
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
if(resp.StatusCode == HttpStatusCode.OK)
{
richTextBox1.AppendText("Login Response Status:" + resp.StatusCode + "\n");
}
else
{
richTextBox1.AppendText("Login Response Failed: " + resp.StatusCode + "\n");
}
request.KeepAlive = true;
result = sr.ReadToEnd();
sr.Close();
}
using (Stream importFile = requests.GetRequestStream())
{
FileStream fs = File.OpenRead(#"data.xml");
byte[] bytes = ReadWholeArray(fs); // turn xml file to byte function
requests.ContentType = "application/x-binary";
requests.Method = "POST";
importFile.Write(bytes, 0, bytes.Length);
}
using (WebResponse responses = requests.GetResponse())
{
StreamReader srs = new StreamReader(responses.GetResponseStream());
result = srs.ReadToEnd();
srs.Close();
}
}
catch (Exception ex)
{
richTextBox1.AppendText("Exception Throw:" + ex.Message);
}
}
I try the python code it request login and send file at the same time.
And below is the code that i don't understand.
files = {'file': (data_xml, open(data_xml, 'rb'), 'application/x-binary', {'Expires': '0'})}

HttpWebResponse not responding from PHP

So I have this code in C#.
private void SendMessage()
{
// this is what we are sending
string post_data = "loginIdPost=" + 2 + "&" + "contentPost=" + absenceInputField.text;
string uri = "<URI IS HERE>";
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(uri); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Debug.Log(new StreamReader(response.GetResponseStream()).ReadToEnd());
Debug.Log(response.StatusCode);
Console.WriteLine(response.StatusCode);
}
It sends some information to a PHP file, which then puts data into my database. The data is being successfully sent, but the HttpWebResponse is coming back blank. It returns "", an empty string.
This is my PHP code.
<?php
//Id
if (isset($_POST["loginIdPost"]))
{
$loginId = $_POST["loginIdPost"];
}
else
{
$loginId = null;
}
//Content
if (isset($_POST["contentPost"]))
{
$content = $_POST["contentPost"];
}
else
{
$content = null;
}
try
{
$conn = new PDO("Connection String");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
print("Error connecting to SQL Server.");
die(print_r($e));
}
$sth = $conn->prepare('Sql Query is here');
$sth->execute('details of execution are here');
echo "Success";
//Check Connection
if(!$conn)
{
die("Connection Failed. ". mysqli_connect_error());
}
?>
Does anyone know why I'm getting an empty string back, when I'd expect to be getting "Success" back. Again, no errors in the php code as the SQL query does insert data into my database.
I managed to fix it by just removing Console.Writeline.

PHP Web API Call Not Working

I have been trying for a while now to connect to my Web API with PHP and getting nothing.
I can connect using C# perfectly and am getting back results. however PHP seems to be a problem for me. I have tried many methods from SO and getting no joy. I'm a C# developer and need to get this PHP code going to PHP developers to connect to our API too.
Here is my PHP Code.
<?php
try {
$client = new SoapClient("https://api.proactiveclothing.com/wsdl/ProductDataService.wsdl");
class parms {
function parms($username, $password) {
$this->wsVersion = 1;
$this->id = $username;
$this->password = $password;
$this->productId = 0;
$this->partId = 0;
$this->isSellable = false;
}
}
$p = new parms("api#xx.co.za", "xxx");
$params = array($p);
$response =$client->__soapCall("getProductSellable",$params);
echo "<b>PASS</b>" . "<br />";
echo $response;
} catch(SoapFault $fault) {
//echo(var_dump($response));
echo "<b>FAIL</b>" . "<br />";
echo $fault . "<br />";
}
?>
This is my C# code which works 100%
private string getProductSellable()
{
ASCIIEncoding encoding = new ASCIIEncoding();
string SampleXml = #"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Body xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<GetProductSellableRequest xmlns=""https://www.proactiveclothing.com/WSDL/ProductDataService/1.0.0/"">
<wsVersion xmlns=""https://www.proactiveclothing.com/WSDL/ProductDataService/1.0.0/SharedObjects/"">1.0.0</wsVersion>
<id xmlns=""http://www.proactiveclothing.com/WSDL/ProductDataService/1.0.0/SharedObjects/"">api#xxx.co.za</id>
<password xmlns=""http://www.proactiveclothing.com/WSDL/ProductDataService/1.0.0/SharedObjects/"">xxx</password>
<productId xmlns=""https://www.proactiveclothing.com/WSDL/ProductDataService/1.0.0/SharedObjects/"">Token1</productId>
<partId xmlns=""https://www.proactiveclothing.com/WSDL/ProductDataService/1.0.0/SharedObjects/"">token1</partId>
<isSellable xmlns=""https://www.proactiveclothing.com/WSDL/ProductDataService/1.0.0/SharedObjects/"">true</isSellable>
</GetProductSellableRequest>
</s:Body>
</s:Envelope>";
try
{
byte[] data = encoding.GetBytes(SampleXml);
string url = "https://api.proactiveclothing.com/services/Product.svc";
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "POST";
webrequest.Headers.Add("SOAPAction", "getProductSellable");
webrequest.ContentType = "text/xml";
webrequest.ContentLength = data.Length;
using (Stream newStream = webrequest.GetRequestStream())
{
newStream.Write(data, 0, data.Length);
using (WebResponse response = webrequest.GetResponse())
using (Stream responseStream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(responseStream);
string s = sr.ReadToEnd();
return s;
}
}
}
catch (WebException webex)
{
return webex.ToString();
}
}
I've disabled the authentication on this method call, if anyone wants to give it a try please.

Retrieve/fetch data to display to my ASP.Net web application from PHP service thats connected to remote MySQL database

So I have a remote(hosted) MySQL database which I connect to with a PHP service. I need both my ASP.Net c# web application and my android to communicate with it. However, I'm struggling with populating my web application template with all the information I retrieve from the service. For instance, I would like to populate a profile page of the user.
Below would be my PHP connection and communication to the database:
`// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Vendor Where VendorId = 2"; //this is just a test
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo . $row["id"]. . $row["BusinessName"]. . $row["Location"]. . $row["Email"]. .$row["Website"]. .$row["ProductType"]. .$row["Contact"]. .$row["PaymentOption"]. .$row["ProfileImg"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
`
and then (without sharing all my setups) this would be the code sample for asp.net c# to communicate with my PHP file/service.
public void getUserInfo(int id)
{
string BusinessName = lblBusiness.Text.Trim();
string email = lblEmail.Text.Trim();
string Contact = lblPhone.Text.Trim();
string location = lblLocation.Text.Trim();
string Website = lblWebsite.Text.Trim();
string payment = lblPayment.Text.Trim();
//Variables to get information from the service
Stream dataStream = null;
WebResponse response = null;
StreamReader reader = null;
//Stores the result from the server
string responseFromServer = null;
try
{
string requestMethod = "GET";
//Sending this data across the stream
string postData = "&Email=" + email + "&BusinessName=" + BusinessName + "&Website=" + Website + "&PaymentOption=" + payment + "&Location=" + location + "&ProductType=" + ProductType + "&Contact=" + Contact + "";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
string URL = "";// url of php service location
string contenttype = "application/x-www-form-urlencoded";
//Create link to web service
WebRequest request = WebRequest.Create(URL);
//Pass the request method
request.Method = requestMethod;
request.ContentType = contenttype;
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
//Get response from the server
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (dataStream != null && reader != null && response != null)
{
dataStream.Close();
reader.Close();
response.Close();
}
//Getting the response from the service
//string result = responseFromServer.ToString();
}
}
also, Im not sure what to return from that function.
Please help.
Your php file is the "API" i pressume.
You basically need to return this from your php file.
$vendorArray = [
"Id" => $row["id"],
"BusinessName" => $row["BusinessName"],
// ... this is just pseudo code, convert the array or take the array or something like that
];
header('Content-type: application/json');
echo json_encode($vendorArray);
then in asp.net you do:
var deserializedVendor = JsonConvert.DeserializeObject<Vendor>(responseFromServer);
Your vendor class has to match your jsonObject to be Deserializable
public class Vendor {
public string Id {get;set;}
public string BusinessName {get;set;}
...
}
it depends on your jsonResponse...
you can also deserialize directly into a complex item with a list of vendors like this:
var allTheVendorsDeserialized = JsonConvert.DeserializeObject<AllTheVendors>(responseFromServer);
public class AllTheVendors {
public bool Success {get;set}
public List<Vendor> {get;set}
}
where php:
$arr = ["Success" => true, $myArrayOfVendors];
header('Content-type: application/json');
echo json_encode($arr);
I believe, your PHP web application is hosted and you can use the PHP service in ASP.NET with the following steps:
WebClient client = new WebClient(); //Create WebClient object
string url = "http://test.com/test.php"; //Get the URL of the PHP service
byte[] html = client.DownloadData(url); //Byte array to hold returned data from the service
Finally use the UTF8Encoding object to convert the byte array into sring:
UTF8Encoding utf = new UTF8Encoding(); //Create an object of the UTF8Encoding class
string str = utf.GetString(html); //Convert data into string

posting data to web pages fails in C#

i have used following code in my c# application
string verification_url = #"http://site.com/posttest.php?";
string verification_data = "test=524001A";
string result = string.Empty;
result = Post(verification_url, verification_data);
public string Post(string url, string data)
{
string result = "";
try
{
byte[] buffer = Encoding.GetEncoding(1252).GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(#url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
result = _Answer.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (result.Length < 0)
result = "";
return result;
}
Server side PHP code
<?php
$test=$_REQUEST['test'];
echo $test;
?>
post method always returns empty value
please help me
try
<?php
print_r($_REQUEST);
?>
to show the raw REQUEST vars. im not sure where you setting test in your c# code.
You need to add the verification data as parameter to the request url eg.
string verification_data = "test=524001A";
string verification_url = #"http://site.com/posttest.php?" + verification_data;
That way your actual request URL would be:
http://site.com/posttest.php?test=524001A
Could you try not closing the RequestStream? Try removing the following line:
PostData.Close();
PS: Do you have the necessary .net permissions to do this?
i have changed the following line
string verification_url = #"http://site.com/posttest.php?";
to
string verification_url = #"http://www.site.com/posttest.php?";
it now works fine

Categories

Resources