-1

So I hava an app which creates a JSON file with some data from the user. This data should be decoded and stored to the database through a PHP script located on my server. I want to post the $_POST variable filename to the php script to use this to retrieve the JSON file. Here is my current PHP script:

<?php
$host='myip';
$user='username';
$pass='userpass';
$db='database';

$link= mysqli_connect($host, $user, $pass, $db) or die(msqli_error($link));

$filename = $_POST['filename'] . '.json';

$json = file_get_contents($filename);
$obj = json_decode($json,true);

foreach ($obj as $data) 
{
$query_opslaan = "INSERT INTO skMain (BedrijfsName, ContPers, TelNum, email, Land, Plaats, PostCode) VALUES ('". $data['bedrijfsNaam'] ."' , '". $data['ContPers'] ."', '". $data['TelNum'] ."', '". $data['email'] ."', '". $data['Land'] ."', '". $data['Plaats'] ."', '". $data['PostCode'] ."')";
}
?>

And this is my JSON file

{
"bedrijfsNaam":"JohnDoeMedia",
"ContPers":"John Doe",
"TelNum":"1234567890",
"email":"test@test.nl",
"Land":"Nederland",
"Plaats":"somewhere",
"PostCode":"1234 AB"
}

I currently only have the upload script in C# but I don't know how to use it to run this PHP script and store data to the PHP variable $_POST['filename'] Here is the store script:

        WebRequest hwr = WebRequest.Create(serverPath);
        hwr.Method = WebRequestMethods.Ftp.UploadFile;
        hwr.Credentials = new NetworkCredential(ftpUser, ftpPass);

        if (reqCat == "bvg")
        {
            json = "{\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
                            "\"ContPers\":\"" + ContPers + "\"," +
                            "\"TelNum\":\"" + TelNum + "\"," +
                            "\"email\":\"" + email + "\"," +
                            "\"Land\":\"" + Land + "\"," +
                            "\"Plaats\":\"" + Plaats + "\"," +
                            "\"PostCode\":\"" + PostCode + "\"}";
            using (var sw = new StreamWriter(hwr.GetRequestStream()))
            {
                sw.Write(json);
                sw.Flush();
                sw.Close();
            }
        }

Can someone please teach me the method to make this work?

B. Hulshof
  • 950
  • 1
  • 13
  • 29
  • That JSON is invalid, it should be an object, not an array. – Jonnix Jun 07 '16 at 14:30
  • But it saves just fine – B. Hulshof Jun 07 '16 at 14:33
  • Also your insert query appears to be missing single quotes around each piece of data. I'd recommend looking a PDO with bound parameters to clean that up. – jszobody Jun 07 '16 at 14:35
  • 2
    The JSON should has curly braces around the data, not square brackets. That's what @JonStirling means by an object instead of an array. Paste your saved JSON at http://jsonlint.com/ and you'll see it's invalid currently. – jszobody Jun 07 '16 at 14:36
  • Ah ok thank you, I`ll edit that real quick – B. Hulshof Jun 07 '16 at 14:37
  • ... it's still in your C# as an array.... – Jonnix Jun 07 '16 at 14:37
  • If any of those data fields ever contain a single quote, your query will break. – jszobody Jun 07 '16 at 14:38
  • I always use queries like this and they work fine – B. Hulshof Jun 07 '16 at 14:38
  • 2
    Sure, they work. Most of the time. You're just playing russian roulette with SQL. Not safe. – jszobody Jun 07 '16 at 14:39
  • What is your actual question? What's not working? Btw, you don't actually run your insert query. None of your code actually seems to fit together. – Jonnix Jun 07 '16 at 14:40
  • I know, I didn't even mention that nothing worked. I just asked how I can use C# to store data to $_POST['filename'] – B. Hulshof Jun 07 '16 at 14:41
  • Looks like you're good then? Now with the curly braces, jsonlist.com says you have valid JSON. PHP should be able to decode it now successfully and do something with it. – jszobody Jun 07 '16 at 14:44
  • I know, and now the question is, what method do I need to use to store C# data to the $_POST['filename'] variable? – B. Hulshof Jun 07 '16 at 14:46
  • Maybe [this answer](http://stackoverflow.com/a/10027534/660694) will help? It shows how to post using C# (I'm a php dev myself, not c#). You can modify that to just post a `filename` param, or you could adapt your own code to post the JSON data instead of write it to disk. – jszobody Jun 07 '16 at 14:49

1 Answers1

1

I'm going to take a stab at this because I think you are possibly confused. You mention you are trying to POST the data but your code shows you are trying to FTP directly to the server.

I've included code I've used to FTP to a server. If you actually want to post via a web service call this won't do that.

        FtpWebRequest lRequest = (FtpWebRequest)WebRequest.Create(serverPath);          
        lRequest.Method = WebRequestMethods.Ftp.UploadFile;
        lRequest.Credentials = new NetworkCredential(ftpUser, ftpPass);
        StreamReader lReader = new StreamReader(json);

        //convert steam to utf8
        byte[] lContents = Encoding.UTF8.GetBytes(lReader.ReadToEnd());
        lReader.Close();

        //Get length of data to post
        lRequest.ContentLength = lContents.Length;

        //Get your request stream
        Stream lRequestStream = lRequest.GetRequestStream();

        //Write to the stream
        lRequestStream.Write(lContents, 0, lContents.Length);

        //Close the stream
        lRequestStream.Close();

        //Get the response from the server
        FtpWebResponse lResponse = (FtpWebResponse)lRequest.GetResponse();

        //What is the actual status.
        MessageBox.Show(String.Format("Upload File Complete, status {0}", lResponse.StatusDescription));

Note you'll have to do the using and whatnot like you are but I have used that code to ftp to a server. I modified it slightly to try and use your variable names though.

Since the request was to use HTTP to send just a filename I've added that to my answer. In the code below the big part is the uri. I am assuming that you can just create your URI to be the web service that runs the php. It would look something like... Where SERVERPATH is your server with the script.php and assuming the parameter your php script is looking for is called FileName. The code also includes handling responses from the server but you might not need to do that depending on what you want the server to do.

Also note that the accept and content type is probably not relevant unless you are expecting a return from the server. The two lines you are mostly concerned with are the WebRequest.Create(xUri) and the lRequest.GetResponse() to actually execute your web request.

http://SERVERPATH/PHP_SCRIPT?FileName=FILENAME

private void CallWebApi(String xUri)
    {
        String lResults;
        using(WebClient lClient = new WebClient()) {
            try {
                HttpWebRequest lRequest = (HttpWebRequest)WebRequest.Create(xUri);
                lRequest.Accept = "application/json";
                lRequest.ContentType = "application/json";
                HttpWebResponse lResponse = (HttpWebResponse)lRequest.GetResponse();
                using(StreamReader lJsonReader = new StreamReader(lResponse.GetResponseStream())) {
                    lResults = lJsonReader.ReadToEnd();
                }

                lRequest = (HttpWebRequest)WebRequest.Create(xUri);
                lRequest.Accept = "application/xml";
                lRequest.ContentType = "application/xml";
                lResponse = (HttpWebResponse)lRequest.GetResponse();
                using(StreamReader lXMLReader = new StreamReader(lResponse.GetResponseStream())) {
                    lResults = lXMLReader.ReadToEnd();
                }

            }
            catch(Exception lException) {
                MessageBox.Show(lException.Message);
            }
        }
    }