4

So I'm using a webclient to send some data from my C# application to my PHP script, which is located on a remote server. The problem that I'm having is that the NameValueCollection I'm using to store my data in works, But whenever my PHP script hits the object switch then it says that the type is invalid, this basically meanse that the switch goes to the default statement.

This is the code from my C# application:

        private static void send_it(string jobj)
        {   
                // this is where I encode my JSON object to base_64
                var b64bytes = System.Text.Encoding.UTF8.GetBytes(json);
                b64encode = System.Convert.ToBase64String(b64bytes);
                var data = new NameValueCollection();
                // this is where I add the data
                data["b64string"] = b64encode;
                data["filename"] = dt.bedrijfsNaam;

                using (WebClient client = new WebClient())
                {
                    var sendB64 = client.UploadValues("http://theurl/script.php", "POST", data);
                }               
        }

(Sorry for my bad code layout, this got a little messed up when I synced with github)

this is what my jobj parameter would look like:

json = "{\"type\":\"" + cat + "\"," +
                "\"bedrijfsNaam\":\"" + dt.bedrijfsNaam + "\"," +
                "\"omzet\":\"" + dt.Omzet + "\"," +
                "\"nieuweklanten1\":\"" + dt.NieuweKlanten + "\"," +
                "\"propsects\":\"" + dt.skProspects + "\"," +
                "\"hotprospects\":\"" + dt.skHotProspects + "\"," +
                "\"afsprakenmaken\":\"" + dt.afsMak + "\"," +
                "\"afspraken\":\"" + dt.afs + "\"," +
                "\"offertesmaken\":\"" + dt.offMak + "\"," +
                "\"gescoordeoffertes\":\"" + dt.gescOff + "\"," +
                "\"nieuweklanten2\":\"" + dt.newKlant + "\"}";

and this is a portion of my PHP script:

if($link ->connect_errno) {
    echo 'ERROR: no connection!';
} else {
    if(isset($_POST)) {
        $obj = json_decode(base64_decode($_POST['b64string']));
        $cat = $obj->type;
        switch($obj->type) {
            case 'main':
                $database = 'SalesKicker';
                $pre = 'INSERT INTO ' . $database['main'] . ' VALUES ';
                store_main_data($pre);
                break;
            case 'second':
                $database = 'SalesKicker';
                $pre = 'INSERT INTO ' . $database['second'] . ' VALUES ';
                store_sec_data($pre);
                break;
            default:
                echo 'ERROR: Invalid Category'
                break;
        }   
        print_r($obj);
    } else {
        echo 'ERROR: no data! <br>
                The object returns: <br>';
        vardump($obj);
    }
}

function store_sec_data($pre) {
    $query_save = $pre . "('" . $obj->bedrijfsNaam ."' , '". $obj->omzet ."' , '". $obj->nieuweklanten1 ."' , '". $obj->prospects ."' , '". $obj->hotprospects ."' , '". $obj->afsprakenmaken ."' , '". $obj->afspraken ."' , '". $obj->offertesmaken ."' , '". $obj->gescoordeoffertes ."' , '". $obj->nieuweklanten2 ."')";
    save($query_save);
}
function save($query) {
    mysqli_query($link, $query) or die(mysqli_error($query));
}

This PHP script gets an empty POST and that's why it goes directly to the else statement. The thing is that my application actually sends POST data, I have tested this with Fiddler, but the script says that $_POST looks like this: "array(0) { }"

The goal of my application:

The goal of this API is that it will store its data to my database, which does not happen for some reason.

What am I doing wrong? Am I sending the data the wrong way? can someone please tell me the right way of doing this? Thanks in advance!

UPDATE:

For those who know something about Fiddler. These are the results of my app activity:

Send result: enter image description here [![enter image description here][2]][2]

As requested by CodeCaster, the data from the RAW tab in fiddler:

The $_POSTArray
(
[b64string] => eyJ0eXBlIjoibWFpbiIsImJlZHJpamZzTmFhbSI6IlRFU1QiLCJDb250UGVycyI6IlRFU1QiLCJUZWxOdW0iOiIxMzM3IiwiZW1haWwiOiJURVNUIiwiTGFuZCI6IlRFU1QiLCJQbGFhdHMiOiJURVNUIiwiUG9zdENvZGUiOiJURVNUIn0=
)
The $_REQUESTArray
(
[b64string] => eyJ0eXBlIjoibWFpbiIsImJlZHJpamZzTmFhbSI6IlRFU1QiLCJDb250UGVycyI6IlRFU1QiLCJUZWxOdW0iOiIxMzM3IiwiZW1haWwiOiJURVNUIiwiTGFuZCI6IlRFU1QiLCJQbGFhdHMiOiJURVNUIiwiUG9zdENvZGUiOiJURVNUIn0=
 )
 The $obj stdClass Object
 (
 [type] => main
 [bedrijfsNaam] => TEST
 [ContPers] => TEST
 [TelNum] => 1337
 [email] => TEST
 [Land] => TEST
 [Plaats] => TEST
 [PostCode] => TEST
 )
 string(89) "INSERT INTO SalesKicker (BedrijfsNaam, ContPers, TelNr, Email, Land, Plaats, POC) VALUES "
 string(146) "INSERT INTO SalesKicker (BedrijfsNaam, ContPers, TelNr, Email, Land, Plaats, POC) VALUES ('TEST' , 'TEST', '1337', 'TEST', 'TEST', 'TEST', 'TEST')"
20
  • have you tried webclient.UploadString()? Commented Oct 5, 2016 at 13:23
  • Executing the code with Fiddler running will show you exactly whats getting sent. Commented Oct 5, 2016 at 13:25
  • @Jacobr365 I know what you mean, but I think that only works with JSON, and as you can see I'm encrypting my JSON object with base_64. Commented Oct 5, 2016 at 13:26
  • @AlexK. Sorry for the late answer, but the fiddler says that it sends the b64 string and filename correctly. So something must be wrong with my PHP script Commented Oct 6, 2016 at 12:28
  • 1
    It's not good how the scope of this question changes with every comment and subsequent edit. It has in the meantime been proven that neither WebClient nor PHP are broken, that the POST is working just fine, but that in fact the problem is in your code. The problem as of NOW is that "the switch doesn't work". I can assure you that PHP's switch() ain't broken either. If the var_dump($obj) does in fact show [type] => main as shown in your output, then the switch will function exactly as intended. Please read How to Ask and start over with this question, it's currently unanswerable, I'm afraid. Commented Oct 13, 2016 at 12:08

3 Answers 3

2
+25

What are you adding a Content-type header to the request?

The default (in .NET - your library may be different) is application/x-www-form-urlencoded which is designed for regular forms/simple data.

It should be fine with base64 data, but you could try setting the header to multipart/form-data as this handles more complex (and longer) data elements.

If you are using another Content-type header then the data will be in the body of the message, and not in $_POST. Have a look at $contents = file_get_contents('php://input'); to see if it's in there and process yourself from $contents.

Sign up to request clarification or add additional context in comments.

2 Comments

Whenever I try and change the request header to something else it throws an exception with the following message: "An unhandled exception of type 'System.Net.WebException' occurred in System.dll Additional information: The Content-Type header cannot be changed from its default value for this request."
Check out the image which I added to my question, this might clear some things up.
1

If you are sure that there is an issue with your PHP code to retrieve data then you can have below options to fix the issue..

  1. You can debug your php script for receiving data by below code before your $_POST data retrieval..

    if($link ->connect_errno) {
        echo 'ERROR: no connection!';
    } else {
        echo "<pre>";
        var_dump($_POST); // then check for var_dump($_REQUEST);
        die("debugging request");
        if(isset($_POST['b64string'])) {
            $cat = $obj->type;
            switch($cat) {
            //Do existing PHP operation
    
  2. Use $_REQUEST instead of $_POST to retrieve data which is not recommended option.

    if($link ->connect_errno) {
        echo 'ERROR: no connection!';
    } else {
        if(isset($_REQUEST['b64string'])) {
            $cat = $obj->type;
            switch($cat) {
            //Do existing PHP operation
    
  3. Use this code to retrieve data file_get_contents('php://input').

    if($link ->connect_errno) {
        echo 'ERROR: no connection!';
    } else {
        content = file_get_contents('php://input');
        if(isset($content)) {
            $cat = $obj->type;
            switch($cat) {
            //Do existing PHP operation
    

Also you need to take care in mysql query that use `` for encoding field value instead of '' while inserting data in the database query.

2 Comments

Check out the image which I added to my question, this might clear some things up.
Also you need to take care in mysql query that use `` for encoding field value instead of '' while inserting data in the database query.
1

I got it,

The thing is, is that the data which my application has sent to my API was valid, and everything worked, except for the sql query.

I had to use this:

function save($query) {
    global $link;
    mysqli_query($link, $query) or die(mysqli_error($query));
}

and not this:

function save($query) {
     mysqli_query($link, $query) or die(mysqli_error($query));
}

This solved my problem.

TIP:

Never use Client.DownloadString(); for debugging your API. This will confuse you, like it did with me.

2 Comments

The other thing when testing API endpoints like this is to de-couple your testing, since you're trying to test sending (from your application) and receiving (with your PHP) at the same time. You would be better off using Postman or hurl.it to test the receiving code independently of the sending code so you can isolate where the issue is more effectively.
ya i also had this issue already,but now cleared thank you @B. Hulshof

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.