2

My purpose is to send JSON from C# to PHP and then further decode it on PHP side to use it for my purpose.
Error at PHP end is:

Warning: json_decode() expects parameter 1 to be string, array given in /home3/alsonsrnd/public_html/test/sync.php on line 24

I am using the following code to send JSON to my PHP code using C#:

  private void sendData()
     {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://alnnovative.com/test/sync.php");
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"user\":\"test\"," +
                          "\"password\":\"bla\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
        }
    }

On PHP I am using strip slashes and json_decode() in order to decode JSON. My PHP code gives error that the received string is an array instead of JSON and thus it cannot use json_decode to decode it. What could be the reason of it? As I am sending the correct format of JSON from C#

My PHP code is:

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $json=$_POST;
    if (get_magic_quotes_gpc()){
        $json = stripslashes($json);
    }

    //Decode JSON into an Array
    $data = json_decode($json);
}
Random
  • 3,158
  • 1
  • 15
  • 25
Sarah Mandana
  • 1,474
  • 17
  • 43

1 Answers1

0

Firstly, you have to change your Content-Type header

httpWebRequest.ContentType = "application/x-www-form-urlencoded";

Secondly, you are sending data in wrong format

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "json=" + "{\"user\":\"test\"," +
                              "\"password\":\"bla\"}"; ;

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

And finally, you are receiving data in wrong way, $_POST is an array, so

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['json']))
{
    $json=$_POST['json'];
    if (get_magic_quotes_gpc()){
        $json = stripslashes($json);
    }
    //Decode JSON into an Array
    $data = json_decode($json, true);
}
Szymon D
  • 441
  • 2
  • 13