Saturday, December 27, 2014

How To Write A Simple PHP/MySQL Web Service for a C# Application

Posted By: Achchuthan Yogarajah - 12/27/2014 06:59:00 AM

Share

& Comment

Creating a basic web service is very simple and encourages your users to spread the word about your website or service. Want more traffic? Want your website to grow without you putting in all the effort? Create a web service!

Web services are taking over the world. Why not use the same model for your own sites? Here's how to create a basic web service that provides an XML or JSON response using some PHP and MySQL.

As a C# Application developer, it can be really useful to be able to write your own simple web services that integrate with your application.
For example, you may wish to display some news updates that come from your web server, and display it on startup. Or perhaps store some user data “in the cloud”. Your imagination is the only limit!

In this first tutorial you’ll go step-by-step through the process of creating a simple web service. I included in my latest application.

How it works?


Download Project 

Step 1: Creating the Database

The first step of this project is to create the database tables you’ll need. For the purposes of this tutorial, you’ll need create database tables:

Database name: simplerestful
Create a database simplerestful and create a table testdata /upload this testdata.sql file into the databse.

testdata.sql
-- phpMyAdmin SQL Dump
-- version 4.0.4.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Feb 11, 2014 at 03:55 PM
-- Server version: 5.6.11
-- PHP Version: 5.5.1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `simplerestful`
--

-- --------------------------------------------------------

--
-- Table structure for table `testdata`
--

CREATE TABLE IF NOT EXISTS `testdata` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `age` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

--
-- Dumping data for table `testdata`
--

INSERT INTO `testdata` (`id`, `name`, `age`) VALUES
(10, 'Achchuthan', '24'),
(11, 'Rajh', '23');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Step 2: C# Application  code for send String to the Server

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SimpleRESTful
{
    public partial class Form1 : Form
    {
        //this is proxy setting 
        private bool proxy_setting = false;//not connected with proxy server

        //this is your proxy username,password,ip
        private string proxy_ip = "http://192.168.1.1";//your proxy server
        private string port = "80"; //proxy password
        private string username = "username"; //proxy username
        private string password = "password";  //proxy password 
 
        //this is for where you want to pass your date URL
        private string post_url = "http://localhost/SimpleRESTful/cash.php";
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string name = textBox1.Text; //get name from text box
            string age = textBox2.Text; //get name from from text box 
            label3.Text = "POST data { Name :" + name + "  Age : " + age + " }";

            //this is your post data

            string POST_DATA = "name=" + name + "&age=" + age;
            
            //sent data to remote server
           string responseString = DataRequestToServer(POST_DATA, post_url);//get responce message from remote server

            //show the responce message
           MessageBox.Show(responseString,"Message from Server");

        }
        public string DataRequestToServer(string postData, string url)
        {
            try
            {
                // Create a new request to the mentioned URL.    
                HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
                if (proxy_setting == true)
                {
                    connectProxy(httpWReq);
                }
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(postData);
                httpWReq.Method = "POST";
                httpWReq.ContentType = "application/x-www-form-urlencoded";
                httpWReq.ContentLength = data.Length;
                using (Stream stream = httpWReq.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
                string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                return responseString;

            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        public void connectProxy(HttpWebRequest httpWReq)
        {
            // Obtain the 'Proxy' of the  Default browser.  
            IWebProxy proxy = httpWReq.Proxy;
            WebProxy myProxy = new WebProxy();
            Uri newUri = new Uri(proxy_ip);
            // Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
            myProxy.Address = newUri;
            // Create a NetworkCredential object and associate it with the  
            // Proxy property of request object.
            myProxy.Credentials = new NetworkCredential(username, password);
            httpWReq.Proxy = myProxy;
        }

        
    }
}

Step 3:  PHP Receiver Code

GET vs POST
Now that we know things are working, it’s almost time to implement the full behavior. But first, let’s talk about our strategy for the web service.
We know we need to pass some data from the c# application to our web service. Specifically, we need to tell the web service the name of the application.
But how can we pass this data? If you aren’t familiar already, there are two ways to pass data to a web service – via GET (the normal way), or via POST (typically used for posting data to a web form).

Depending on which one you choose, the parameters get passed differently:
If you choose GET, the parameters are part of the URL.
If you choose POST, the parameters are passed as part of the request body.

config.php

Database connection configuration code 
$con=mysqli_connect("localhost","root","","simplerestful");
 if (mysqli_connect_errno()){
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }


cash.php

With the number of persons hitting your web service (hopefully), you'll need to do adequate validation before attempting to connect to the database to avoid injection attacks. Once we get the desired results from the database, we cycle through the results to populate our return results array. Depending upon the response type desired, we output the proper header and content in the desired format.

Using post method to get post data from C# Application

require_once("config.php"); 

if (isset($_POST['name'])) {
    $name = $_POST['name'];
 $age = $_POST['age'];
    mysqli_query($con, "INSERT INTO `testdata` (`name`, `age`) VALUES ('$name', '$age')"); 
    echo "Welcome ! $name";
}

You should be able to understand the general idea of how things work here by looking at the comments inline with the code Also, here’s a few things I’d like to point out:

  • isset is a handy function in PHP you can use to tell if a particular variable has been set. We use it here to make sure all the required POST parameters are passed in.

About Achchuthan Yogarajah

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Believe in Yourself - Achchuthan Yogarajah ACHCHUTHAN.ORG. Designed by Templateism .