C# PHP Communication ( Get / Send Data from C# to PHP )

Hi , Have a good day.

This Piece of code will allow you, to Get information from Web page or Send Information to it, By Using POST method trough C# to a PHP Page.

C#—-> Send Data —-> PHP Page —-> Processing Data —-> C# Get Information.

Let me Show you the code

Usage Example , C# Code:

using System;

class Program
    static void Main(string[] args)
        string Data = Web.GetPost("http://www.smart-arab.com/example.php", "UserName", "Me", "Password", "123");

PHP Code:

Please remove the comment from the PHP code before using it.

C# Class : ( You don’t need to go through it deeply, just add it to your Project as a Class file )

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

class Web
    public static string GetPost(string Url, params string[] postdata)
        string result = string.Empty;
        string data = string.Empty;

        System.Text.ASCIIEncoding ascii = new ASCIIEncoding();

        if (postdata.Length % 2 != 0)
            MessageBox.Show("Parameters must be even , \"user\" , \"value\" , ... etc", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            return string.Empty;

        for (int i = 0; i < postdata.Length; i += 2)
            data += string.Format("&{0}={1}", postdata[i], postdata[i + 1]);

        data = data.Remove(0, 1);

        byte[] bytesarr = ascii.GetBytes(data);
            WebRequest request = WebRequest.Create(Url);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytesarr.Length;

            System.IO.Stream streamwriter = request.GetRequestStream();
            streamwriter.Write(bytesarr, 0, bytesarr.Length);

            WebResponse response = request.GetResponse();
            streamwriter = response.GetResponseStream();

            System.IO.StreamReader streamread = new System.IO.StreamReader(streamwriter);
            result = streamread.ReadToEnd();
        catch (Exception ex)
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        return result;

Happy Posting :)


  1. wow, as much as some people might consider this old, actually it works even in 2018 and i know about all the methods that people mentioned above but believe me when i tell you it can be very tricky to link your c# app with a joomla website. and this did the trick form me… Thanks a Lot for Sharing This…

  2. Hey man, how would i send date like this dunno where to start

    string targetURL = “https://www.example.com/hidden-tear/write.php?info=”;
    string userName = Environment.UserName;
    string computerName = System.Environment.MachineName.ToString();
    string userDir = “C:\\Users\\”;
    dont know how to code the php either

  3. I tried this code just like write. But, I don’t get anything in php page. Can you help me with this. I need to get some param from my C# app, and save that param in my web database.

  4. I’m not going to spoon feed this old post but I figured I should maybe just help out a bit for those that are still trying to figure a way to send more than one type of data back to C#. Basically php and C# can not directly send data back and forth from a website to an application. The best approach for this is to use JSON. I would suggest reading up on PHP/JSON and C#/JSON … Taken from Wiki “JavaScript Object Notation, is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs.” Using JSON will help you send multiple values in string based format that you can deserialize into a C# class.

    Example: PHP JSON

    'name' : 'ben',
    'age' : 22

    C# code will receive that as a string type which you can then deserialzie into a class.
    Example: C# Class

    public class UserData
    public string Name { get; set; }
    public int Age { get; set; }

  5. you have made my life so much easier i just modified your script to send a file and its size

    all i did was replace the string in the form value pair with my base64 encoded data

    you allowed me to negate outputting to a file and if the buffer is a certain length post data

    which in turn will be sanitized and passed to mysql bro love you no homo
    you saved me days of work thanks

  6. i have created all the files according the examples. but username and password not displaying in my php page.

    what i want to do is i want to post a variable from C# application which is developed using visual studio to php page which is hosted in the free host site.

    i tried the above example. but i didn’t get the variable to php page.

    whats would be the mistake.

    please help!!!!!!!


  7. Pingback: Gilbert
  8. and what code on c# client to catch both the echoed data in separate variables just like php catches the posted variables in separate variables?

  9. So how to send two values say $name and $age from script to c#.
    Do I have to use two echo commands for this???

  10. In short, just like as we can post multiple values to php script from c# application in one go, for example name, password, age ,date etc.
    How to do the reverse, i.e. how to send multiple values back from one php script to a c# application?
    Need your help!!!

    1. The Only way to read values and variables by C# client is to use echo command in PHP .
      The C# Client read all the output of the PHP script if they are in echo command.

  11. Well, thanks!
    I got it.
    Well what about I want to return actual variables or objects from php?
    I mean suppose I don’t want php to just display an output on the client, but I want to send some data values that can be actually compared and used inside the program.
    For example just suppose that I want to return some error code say code001 or code002 or code003 or some integer value like 0 or 1 or 2 etc like this. Based on this received data I want c# to go to a particular case in a switch statement or something like that.
    So can php be used to send variables or data types that are known to c#.
    Also what about if I want to submit more that one data from a script, for example I want to submit the name and age of a particular user via a script. So how multiple data can be sent from a php script.
    Of course the method discussed in the above tutorial can be used directly or indirectly in all the situations I asked above, but I want to know what is the proper or optimal way to accomplish these tasks!
    I am a beginner to php so please let me know wherever I am wrong.
    Thanks a lot
    Waiting for your response…:)

  12. thanks
    thanks a lot for the help
    i didnt know that just an echo command will do this task!
    well just for the curiosity the code that u wrote for the C# is working good.
    But one of my friends suggested me something like this before I saw your reply:
    01//Get the responce
    02response = request.GetResponse();
    04// Get the stream containing content returned by the server.
    05dataStream = response.GetResponseStream();
    07//Open the responce stream:
    08reader = new StreamReader(dataStream);
    10//read the content into the responcefromserver string
    11responseFromServer = reader.ReadToEnd();
    13// Clean up the streams.
    19//Now, display the responce!

    Can u please explain me the basic difference???
    Thanks once again!!!
    Your reply really means a lot to me…:)

    1. Your Friend is right, But there is no need to rewrite his code,
      I already wrote that code in my class, ( this how I read the echo output from PHP )

      Please check my class code.

  13. Thanks for the tutorial.
    But can you please tell me how to send the data back from php to c#.
    Suppose the php script received the posted username and password.
    Now we checked the password with an sql query in the php script.
    Now the problem comes, suppose I want to infrom the C# client that your password is correct/incorrect. So what code should be witten in php to accomplish this.
    I am ok with the queries and all other php code only thing I need to know is what code should be their in script to reply back to the C# client.
    And how C# will catch that reply.
    Many Thanks!

    1. If I understand you correctly, You can parse the return data from the function “GetPost”.
      For example :

      1- send the password from c# to php.
      2- let the php code check the password if it is correct or incorrect.
      3- if the password not correct ( echo “password is incorrect” ) //use this code in PHP
      4- if the password is correct ( echo “password is correct” ) //use this code in PHP
      5- parse the string values (Data) in c# ( string Data = Web.GetPost(“www.website.com/postvalue?somthing”) )
      The Data Variable will return with value “password is incorrect” or “password is correct”;
      Hope this help .

  14. it would be nice if the request for more comments in the c# code could be acknowledged. It is confusing to see where the “UserName” in “$_POST[‘UserName’]” is coming from. Is that the name used to represent the value inside the “string[] postdata” array?…

    1. Take a look at this line of code

      Web.GetPost("www.smart-arab.com/example.php", "UserName", "Me", "Password", "123");

      it’s said like this
      1-“WebSite URL”.
      2-“Post Variable” , 3-“It’s Value” , 4-“Post Variable” , 5-“It’s Value”

      The Post Variable Must be identical inside C# and PHP code.
      For Example :

      “UserName” in c# code match “Post Variable” in PHP code $_POST[‘UserName’]
      (those must be changed together)
      And The User Name Value which in our case is “Me” , could be anything “Admin” , “Sarah” … etc, This value will be send from C# to PHP.

      Again “Password” in c# code match “Post Variable” in PHP code $_POST[‘Password’]
      (those must be changed together)
      And Again The Password Value which in our case “123” could be any thing “1904” , “SuperPass” , etc … This value will be send from C# to PHP.

      if you need more explain please let me know …

  15. Pingback: micro jobs

Leave a Reply

Your email address will not be published.