Transferring JSON data back and forth between C# and PHP files

I am trying to send a JSON request from C# to a PHP file in order to save data into a text file. However, the PHP file is unable to read the data. Below is my code:

User user = new User { id = 1, name = "Bob", address = "password", phone = "0111111111", activation = true };
                string json = "{\"id\":" + "\"" + user.id + "\""
                        + ",\"name\":" + "\"" + user.name + "\""
                        + ",\"address\":" + "\"" + user.address + "\""
                        + ",\"activation\":" + "\"" + user.activation + "\"}";

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test.php");

                request.Method = "POST";
                request.ContentType = "application/json";
                request.ContentLength = json.Length;

                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(json);
                    streamWriter.Close();

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

The PHP file content:

<?php
$data = json_decode(file_get_contents('php://input'), true);

$file = "LogFile.txt";
$handle = fopen($file, 'a') or die('ERROR: Cannot write to file: ' . $file);
date_default_timezone_set('Europe/Amsterdam');

fwrite($handle, $data); 
fclose($handle);
echo "SUCCESS";

What changes should I make in the PHP file to properly read the data? Thank you.

Answer №1

After trying various solutions, I finally found the simple code snippet that resolved my issue:

$incoming_data = json_decode(file_get_contents('php://input'), true);

if (isset($incoming_data)) {
    $file = "users.txt";
    file_put_contents($file, json_encode($incoming_data));
} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to transfer the value of a JavaScript variable to a PHP variable

Similar Question: How can I transfer JavaScript variables to PHP? I am struggling to assign a JavaScript variable to a PHP variable. $msg = "<script>document.write(message)</script>"; $f = new FacebookPost; $f->message = $msg; Unfort ...

Attempting to modify a JSON file within a React application

I recently obtained a JSON file named 'DealerList.json' which I managed to import into my app using the following code snippet: import DealerList from './json/DealerList' let tasks = DealerList; The tasks now store the JSON data and I ...

Struggling to convert a JSON file into a TableView within a JavaScript application developed with Appcelerator

Trying to display a JSON file in a table using JavaScript and Appcelerator is proving to be quite a challenge. The output appears as an empty table when compiled to an example page. As someone relatively new to JavaScript and JSON, I'm seeking guidanc ...

The error message java.lang.NumberFormatException: Unable to parse the input string: "2017-01-28 13:28:20" occurred

During the execution of my java project, I encountered an error with a Gson deserializer function. The error message states: java.lang.NumberFormatException: For input string: "2017-01-28 13:28:20" at java.lang.NumberFormatException.forInputString(NumberF ...

Barryvdh/laravel-domPDF is causing an error where it attempts to read the property "name" on a boolean value

Currently, I am utilizing Laravel 8 with PHP 8 in addition to barryvdh/laravel-domPDF. The issue I am facing involves a CRUD that showcases employee details and allows for the printing of their payslips. It functions correctly when not passing through the ...

Establishing a Secure Connection between PHP Server and Amazon AWS MySQL Server

Currently, I have set up two servers on Amazon AWS. One server is dedicated to running PHP while the other handles MySQL. Accessing the MySQL database through my terminal and MySQL Query Browser has proven successful. However, I am facing challenges in es ...

I am experiencing an issue where the CSS file in the wwwroot directory does not update when I make changes to the code in ASP.NET MVC

Here is a link to my CSS file: Click here for image description This is how the file looks when built (no changes): Click here for image description Occasionally, running "clean-solution" and "build-solution" fixes the issue, but it's not working no ...

Showing small previews of images using php

I'm struggling with getting linked images to display. The code I have is currently located in a .php file. Its purpose is to retrieve all images from the directory where the file resides and show them using a "for" loop. However, at the moment, it onl ...

Is there a way to send a multi-dimensional array using jQuery ajax?

I am encountering an issue with posting an array as a JavaScript variable {{0,0},{1,1},{2,2}} using JSON.Stringify. Whenever I try to post it, I receive an internal server error 500. Can someone please advise on how I can successfully post and utilize this ...

Retrieve the precise response parameter using urllib in Python

Is there a way to process the token information obtained from a web request using urllib in Python? from urllib import request from urllib.parse import urlencode response = request.urlopen(req, data=login_data) content = response.read() The response typic ...

Steps to create a personalized value for a column in a MySQL query

During the exam, I am dealing with 2 tables. 1) Post - and its columns : pid : uid : title : content : created date : ... 2) URL alias aid : sou_url : des_url : The purpose of the second table is to store URL aliases for all pages on my website. I have ...

Tips for processing JSON data in a Flutter application when the response consists of an array of objects

I received an API response structured like this: [ {"name":"lakshay","id":"1217","type":"Staff","temperature":56.6,"date":"12-06-2020"}, {"name":"lakshay","id":"1217","type":"Staff","temperature":56.6,"date":"12-06-2020"}, ..... ] I want to ...

Is there a way to display (PHP for loop variables) within an HTML table using echo?

for ($q = 1 ; $q < 7 ; $q++ ) { echo $q ; echo $row; } While the above code functions properly, I am interested in echoing two rows as shown in the image below: https://i.stack.imgur.com/7KmUY.jpg I prefer not to use another for loop. Is there a way t ...

convert and transform XML data into JSON format

I have been working with nodejs-expressjs and I received a response in raw XML format. My goal is to convert this raw XML into either a JavaScript array or a JSON array so that I can extract the domain name along with its status. I want to display this inf ...

Converting Python dictionary to JSON format

As I am still new to Python programming, please excuse any mistakes I may make I'm attempting to create a json file using 2 dictionaries and write the output to the file with the code provided below on Windows import json import sys import string f ...

Steps to Safely Transmit the Password through Ajax() Function in jQuery

I have implemented a Password textbox that starts with an empty value. When the user clicks on it and enters a password, the password will be updated in the database upon leaving the textbox (onblur event). I have successfully achieved this using ajax(). H ...

ListException: 'list' object does not support the 'get' operation

This is the code snippet: def validate_record_schema(record): device = record.get('Payload', {}) manual_added= device.get('ManualAdded', None) location = device.get('Location', None) if isinsta ...

Tallying the number of keys within the JSON

Here is an example of a JSON object: var json = { "pages": [{ "name": "page1", "elements": [{ "type": "text", "name": "question1" }, { "type": "text", ...

Assessment and designation within the if condition

I am curious to know if this code will function properly with all major versions of PHP? if ($foo != $bar && '' != $str = some_function($some_variable)) echo $str; The some_function($some_variable) returns a string, which is assigne ...

How to generate a custom JSON key name in PHP using Laravel

Currently, I am utilizing imagick to extract a number of pages and then store it in JSON format. However, the number is stored as is without any key, for instance - 20. I am seeking a way to store the number with a specific key like below: { "pages": " ...