I have a PHP script which get it's post data from my C# code. My C# code sends POST data to my PHP script including a base64 string and a filename. With these two pieces of data it should create a JSON file in the folder JSON with the filename and then it should write the decoded base64 string to the file it just created. After this it should save the JSON data to a database. But there's one problem, It doesn't create the JSON file and it saves blank data to my database. Here is what I have so far:
PHP:
<?php
$link = new mysqli($host, $user, $pass, $db);
if($link ->connect_errno)
{
echo 'Database connection wrong<br/>';
}
else
{
if(isset($_POST['filename']) && isset($_POST['b64string']))
{
$jsonstring = base64_decode($_POST['b64string']);
$filename = $_POST['filename'] . '.json';
$create = fopen(__DIR__. "/json/" . $filename, "W+");
fwrite($create, $jsonstring);
$json = fread($create, filesize(__DIR__. "/json/" . $filename));
fclose($create);
$obj = json_decode($json);
$query_opslaan = "INSERT INTO SalesKicker (BedrijfsNaam, ContPers, TelNr, Email, Land, Plaats, POC) VALUES ('". $obj->bedrijfsNaam ."' , '". $obj->ContPers ."', '". $obj->TelNum ."', '". $obj->email ."', '". $obj->Land ."', '". $obj->Plaats ."', '". $obj->PostCode ."')";
mysqli_query($link, $query_opslaan) or die(mysqli_error($query_opslaan));
}
else
{
echo 'ERROR: no data!';
}
}
?>
It get's the data from the following C# script:
if (reqCat == "bvg")
{
json = "{\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
"\"ContPers\":\"" + ContPers + "\"," +
"\"TelNum\":\"" + TelNum + "\"," +
"\"email\":\"" + email + "\"," +
"\"Land\":\"" + Land + "\"," +
"\"Plaats\":\"" + Plaats + "\"," +
"\"PostCode\":\"" + PostCode + "\"}";
var b64bytes = System.Text.Encoding.UTF8.GetBytes(json);
b64encode = System.Convert.ToBase64String(b64bytes);
using (WebClient client = new WebClient())
{
byte[] sendB64 = client.UploadData("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST",
System.Text.Encoding.ASCII.GetBytes("b64string=" + b64encode + "&filename=" + dt.bedrijfsNaam));
}
}
This is my folder structure:
public_html (this is where all the PHP stuff is located) -> json (the folder where it should be saved)
I don't really know what to do at the moment so I came here to post my problem. Can someone please help me out and tell me what I'm doing wrong here?
Got it!
You sending 'filename' param in the POST body, but checking it in the GET array. So you don't even go into the your if(){} statement.
You need either change
if(isset($_GET['filename']) && isset($_POST['b64string']))
to
if(isset($_POST['filename']) && isset($_POST['b64string']))
either change in C#
byte[] sendB64 = client.UploadData("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST",
System.Text.Encoding.ASCII.GetBytes("b64string=" + b64encode + "&filename=" + dt.bedrijfsNaam));
to
byte[] sendB64 = client.UploadData("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php?filename=" + dt.bedrijfsNaam, "POST",
System.Text.Encoding.ASCII.GetBytes("b64string=" + b64encode));
I wasn't sure at first but after testing here the solution:
wrong:
$create = fopen(__DIR__. "/json/" . $filename, "W+");
correct:
$create = fopen(__DIR__. "/json/" . $filename, "w+");
It's kind of stupid but capital letters in the mode are not valid. Hope this solves the issue :)
That moment when a C# programmer forgets about the caches. I was a bit clumsy but after searching for the method how to clear a cache in PHP I found it. Behold, the legendary clearstatcache() method. My final working PHP code looks like this:
if(isset($_POST['filename']) && isset($_POST['b64string']))
{
clearstatcache();//the solution to my problem
$jsonstring = base64_decode($_POST['b64string']);
$filename = $_POST['filename'] . '.json';
$create = fopen(__DIR__. "/json/" . $filename, "w+");
fwrite($create, $jsonstring);
$json = fread($create, filesize(__DIR__. "/json/" . $filename));
fclose($create);
$obj = json_decode($json);
$query_opslaan = "INSERT INTO SalesKicker (BedrijfsNaam, ContPers, TelNr, Email, Land, Plaats, POC) VALUES ('". $obj->bedrijfsNaam ."' , '". $obj->ContPers ."', '". $obj->TelNum ."', '". $obj->email ."', '". $obj->Land ."', '". $obj->Plaats ."', '". $obj->PostCode ."')";
mysqli_query($link, $query_opslaan) or die(mysqli_error($query_opslaan));
}
Related
While sent email using below subject which apostrophe replacing with another characters
Actual Subject : We’ll make 100,800 cold calls for you
Mail Shows Subject : We’ll make 100,800 cold calls for you
Issue happens when I'm sent email via api , when sent email from SMTP it's working fine
Please check my api code below
string msg = "From: " + FromName + "<" + From + ">" + " \r\n" +
"To: " + ToName + "<" + To + ">" + " \r\n" +
"BCC: " + BCCEmail + " \r\n" +
"Subject: " + Subject + " \r\n" +
"Message-ID: mID_" + messageID + "\r\n" +
"References: "+encryptMessageID + "\r\n" +
"In-Reply-To: " + encryptMessageID + "\r\n" +
"Content-Type: " + contentType + "; charset=us-ascii\r\n\r\n" + Body;
dynamic objSendMsg = new { raw = commonFunction.Base64UrlEncode(msg) };
if (!string.IsNullOrEmpty(messageThreadID))
objSendMsg = new { raw = commonFunction.Base64UrlEncode(msg), threadId = messageThreadID };
var _objSendMsg = JsonConvert.SerializeObject(objSendMsg);
var strSendMsg = new StringContent(_objSendMsg, UnicodeEncoding.UTF8, "application/json");
When same content i'm applying in body with apostrophe working fine for body
Please check attached screenshot
Email copy
You need to base64_encode of the subject header your sending it as plain text. the API is getting confused.
Subject: " + Convert.ToBase64String(Subject) + " \r\n" +
I have some problem in inserting data to my free webhost mysql using JSON in C#. This is what I have done :
Php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP REQUEST Request
*/
require_once __DIR__ . '/db_connect.php';
//require_once __DIR__ . '/generateIDrandom.php';
require_once __DIR__ . '/Configuration.php';
$db = new DB_CONNECT();
$connstring = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// array for JSON response
$response = array();
// check for required fields
if (isset($_REQUEST['WSID'])) {
$wsid = $_REQUEST['WSID'];
$jenismesin = $_REQUEST['JenisMesin'];
$merk = $_REQUEST['MerkMesin'];
$lokasi = $_REQUEST['Lokasi'];
$inlok = $_REQUEST['InisialLokasi'];
$limit = $_REQUEST['LimitMesin'];
$denom = $_REQUEST['Denom'];
$tim4 = $_REQUEST['Tim4'];
$tim5 = $_REQUEST['Tim5'];
$status = "1";
// connecting to db
$result = mysqli_query($connstring, "insert into MasterATM (WSID, JenisMesin, MerkMesin, Lokasi, InisialLokasi, LimitMesin, Denom, Tim4, Tim5, Status) values ('$wsid','$jenismesin','$merk','$lokasi', '$inlok', '$limit', '$denom','$tim4','$tim5','$status')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Upload Successfully";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
C#
private void InputBtn_Click(object sender, EventArgs e)
{
try
{
WebRequest request = WebRequest.Create("https://xxx.000webhostapp.com/php/InsertDataMesin.php?WSID =" + WSIDBox.Text + "& JenisMesin = " + TipeMesinBox.SelectedItem + "& MerkMesin = " + MerkMesinCB.SelectedItem + "& Lokasi= " + LokasiBox.Text + "& InisialLokasi = " + InisialLokasiBox.Text + "& LimitMesin= " + LimitBox.Text + "& Denom= " + DenomBox.Text + "& Tim4= '" + Tim4CB.SelectedItem + "& Tim5= '" + Tim5CB.SelectedItem + "& Status = 1");
WebResponse response = request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string json = stream.ReadToEnd();
stream.Close();
var result = JsonConvert.DeserializeObject(json);
MessageBox.Show("Data berhasil ditambahkan !");
TampilDataEdit();
}
catch
{
MessageBox.Show("Data gagal ditambahkan. Silakan coba lagi");
}
}
When I run my program, there is no some error. But when I see to my database, there is no data inserted. So, How can I insert data using json c# ?
So I have a C# script which stores data to a database through my PHP script. My C# script uses WebClient to achieve this effect. But sadly my C# script doesn't send POST data to my PHP script and I don't know why. This is what I have so far:
C#
json = "{\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
"\"ContPers\":\"" + ContPers + "\"," +
"\"TelNum\":\"" + TelNum + "\"," +
"\"email\":\"" + email + "\"," +
"\"Land\":\"" + Land + "\"," +
"\"Plaats\":\"" + Plaats + "\"," +
"\"PostCode\":\"" + PostCode + "\"}";
var b64bytes = System.Text.Encoding.UTF8.GetBytes(json);
b64encode = System.Convert.ToBase64String(b64bytes);
using (WebClient client = new WebClient())
{
byte[] sendB64 = client.UploadData("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST",
System.Text.Encoding.ASCII.GetBytes("b64string=" + b64encode + "&filename=" + dt.bedrijfsNaam));
MessageBox.Show(Encoding.UTF8.GetString(sendB64));
}
PHP
if($link ->connect_errno)
{
echo 'ERROR: no connection!';
}
else
{
if(isset($_POST['b64string']))
{
$jsonstring = base64_decode($_POST['b64string']);
$obj = json_decode($jsonstring);
$query_opslaan = "INSERT INTO SalesKicker (BedrijfsNaam, ContPers, TelNr, Email, Land, Plaats, POC) VALUES ('". $obj->bedrijfsNaam ."' , '". $obj->ContPers ."', '". $obj->TelNum ."', '". $obj->email ."', '". $obj->Land ."', '". $obj->Plaats ."', '". $obj->PostCode ."')";
mysqli_query($link, $query_opslaan) or die(mysqli_error($query_opslaan));
}
else
{
echo 'ERROR: no data!';
}
}
The problem is is that my PHP script returns
"ERROR: no data!"
This should obviously not happen. What should happen is that the PHP gets the POST data and saves it to my Database. Can someone please tell me why this isn't working correctly?
I should use the following c# method except of my current one:
var data = new NameValueCollection();
data["b64string"] = b64encode;
data["filename"] = dt.bedrijfsNaam;
using (WebClient client = new WebClient())
{
var uploadData = client.UploadValues("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST",
data);
response = Encoding.UTF8.GetString(uploadData);
}
I should've been using the NameValueCollection instead of just a string.
I am trying to do PUT method for API service
Here is the code:
WebClient box = new WebClient();
var uuid = "40922d72-57dd-4fa6-bd64-f406f444dbb6";
if (HttpContext.Current.Session["JSESSIONCOOKIE"] != null)
{
}
else
{
return null;
}
box.Headers["Cookie"] = HttpContext.Current.Session["JSESSIONCOOKIE"].ToString();
string sampleJson = "{" + "autoPresetTimes" + ":" + "{" + "0" + ":" + "Night" + "}}".ToString();
string json = new JavaScriptSerializer().Serialize(sampleJson);
Uri uri = new Uri("https://my.zipato.com:443/zipato-web/v2/thermostats/" + uuid + "/config");
box.UploadString(uri, "PUT", json);
My problem is that this above gives me error 500 from server. I think because i dont send my body like this:
{"autoPresetTimes": {
"0": "Night"
}
}
On API page it says Parameter content type: application/json so i guess i should send my response o look like this above.
Any thoughts on this?
The json that you are creating looks incorrect. You need to put your keys within double quotes.
string json =
"{" + "\"autoPresetTimes\"" + ":" + "{" + "\"0\"" + ":" + "\"Night\"" + "}}";
Uri uri =
new Uri("https://my.zipato.com:443/zipato-web/v2/thermostats/" + uuid + "/config");
box.UploadString(uri, "PUT", json);
Note: You do not need to specify port 443 in your url. The default port for https is 443
I'm trying to write a tool to batch upload images to my website, but I'm having trouble receiving (or sending) the actual data to the server.
I'll start with some C# code as it should explain what I'm trying to do better that I can articulate:
private bool Upload( string LocalFile, int ItemID, string Description, DateTime Date, string Photographer )
{
WebClient oWeb = new System.Net.WebClient();
NameValueCollection parameters = new NameValueCollection();
parameters.Add( "Type", "1" );
parameters.Add( "ID", ItemID.ToString() );
parameters.Add( "Desc", Description );
parameters.Add( "Date", Date.ToString( "yyyy-MM-dd" ) );
parameters.Add( "Photographer", Photographer );
oWeb.QueryString = parameters;
var responseBytes = oWeb.UploadFile( "http://www.teamdefiant.co.uk/moveuploadedfile.php", LocalFile );
string response = Encoding.ASCII.GetString(responseBytes);
MessageBox.Show( "Response: \n\n" + response + "\n\nPost Data: \n\n" + LocalFile + "\n" + ItemID.ToString() + "\n" + Description + "\n" + Date.ToString("yyyy-MM-dd") + "\n" + Photographer );
Clipboard.SetText( "Response: \n\n" + response + "\n\nPost Data: \n\n" + LocalFile + "\n" + ItemID.ToString() + "\n" + Description + "\n" + Date.ToString("yyyy-MM-dd") + "\n" + Photographer );
return true;
}
When I receive the response, (as displayed in the MessageBox, and Clipboard.SetText) I get the following data:
Response:
Upload:
Type:
Size: 0kb
Stored in:
Post Data:
C:\Users\<MyFolder>\Pictures\Website\ExampleImage.png
4
Picture Description
2014-12-10
Photographer
And for completeness, here's the php code:
<?PHP
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["myfile"]["error"] . "\n";
}
else
{
echo "Upload: " . $_FILES["myfile"]["name"] . "\n";
echo "Type: " . $_FILES["myfile"]["type"] . "\n";
echo "Size: " . ($_FILES["myfile"]["size"] / 1024) . " Kb\n";
echo "Stored in: " . $_FILES["myfile"]["tmp_name"] . " \n";
echo $_POST["Type"] . " \n";
echo $_POST["ID"] . " \n";
echo $_POST["Desc"] . " \n";
echo $_POST["Date"] . " \n";
echo $_POST["Photographer"] . " \n";
}
?>
I've tried searching for answers but haven't been able to find a working solution that I can understand. (I'm still just learning C#.)
I don't get any code errors in Visual Studio, not do I get any POST errors server side, so I'm stumped.
Any and all help is appreciated!
EDIT
I tried visiting the webpage directly and get the same response, so it looks like no data is being sent to the server?? :(
your c# front-end code doesn't have few things
you need to define a content type octet stream
Client.Headers.Add("Content-Type","binary/octet-stream");
you also need to specify POST in your UploadFile
oWeb.UploadFile ("http://www.teamdefiant.co.uk/moveuploadedfile.php","POST", LocalFile);
try this simple code I found on the internet, create a different work branch and give it a try, this is a lot more basic and in a working condition:
the php script:
<?php
$uploaddir = 'upload/'; // Relative Upload Location of data file
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
echo "File ". $_FILES['file']['name'] ." uploaded successfully. ";
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully moved. ";
}
else
print_r($_FILES);
}
else {
echo "Upload Failed!!!";
print_r($_FILES);
}
?>
and this is the C# code:
System.Net.WebClient Client = new System.Net.WebClient ();
Client.Headers.Add("Content-Type","binary/octet-stream");
byte[] result = Client.UploadFile ("http://your_server/upload.php","POST","C:\test.jpg");
string s = System.Text.Encoding .UTF8 .GetString (result,0,result.Length );