Categories
C# PHP

Posting to HTTP with C#

First, create a WinForms application in Visual Studio.

Add 4 labels, 4 textBox and 1 button as seen above.

Click on button and write the code below. Change YOUR_URL and your_page. This code block will post our params same as HTML forms.

private void button1_Click(object sender, EventArgs e)
        {
            //Request
            System.Net.WebRequest request = System.Net.WebRequest.Create("http://YOUR_URL/your_page.php");
            request.Method = "POST";
            string postData = "name=" + textBox1.Text + "&surname=" + textBox2.Text + "&phone=" + textBox3.Text + "&email=" + textBox4.Text;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            System.IO.Stream dataStream = request.GetRequestStream();          
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();  
            
            //Response            
            System.Net.WebResponse response = request.GetResponse();
            Console.WriteLine(((System.Net.HttpWebResponse)response).StatusDescription);
            using (dataStream = response.GetResponseStream())
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);  
                string responseFromServer = reader.ReadToEnd();
                MessageBox.Show(responseFromServer);
            }
            response.Close();
        }

Here is our your_page.php

<?php
header("Access-Control-Allow-Origin: *");

try {
    $dbh = new PDO("mysql:host=localhost;dbname=DB_NAME", "DB_USERNAME", "DB_PASSWORD");
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

$time = time();
$name = $_POST['name'];
$surname = $_POST['surname'];
$phone = $_POST['phone'];
$email = $_POST['email'];

$sth = $dbh->prepare("INSERT INTO patients (time, name, surname, phone, email) VALUES (?,?,?,?,?)");

$sth->bindParam(1, $time, PDO::PARAM_INT);
$sth->bindParam(2, $name, PDO::PARAM_STR);
$sth->bindParam(3, $surname, PDO::PARAM_STR);
$sth->bindParam(4, $phone, PDO::PARAM_STR);
$sth->bindParam(5, $email, PDO::PARAM_STR);

$create = $sth->execute();

echo "Person recorded.";

You will see response from your_page.php when you submit your form from our C# application.