Search code examples
c#phpwebclientnamevaluecollection

How to POST NULL value C#


I need to POST data from C# WinForms application into PHP page. I'm using WebClient with sample code below:

using (WebClient client = new WebClient())
{
    NameValueCollection values = new NameValueCollection();
    values.Add("menu_parent", null);

    string URL = "http://192.168.20.152/test.php";
    byte[] response = client.UploadValues(URL, values);

    string responseString = Encoding.Default.GetString(response);

    MessageBox.Show(responseString);
}

On the PHP side, I'm doing simple IF condition to test whether the menu_parent is NULL or not with this very simplified code:

<?php
$parent = $_POST['menu_parent'];

if ($parent === null)
    echo "menu_parent is null";
else
    echo "menu_parent is: <".$parent.">"; // This prints out.

if (is_null($parent))
    echo "menu_parent is also null";
else
    echo "menu_parent is also: <".$parent.">" // This also prints out.

if ($parent === "")
    echo "menu_parent is empty string"; // This also prints out.
else
    echo "menu_parent is not empty";
?>

The problem is the NULL value of menu_parent is converted into empty string in the PHP page. I've checked the MSDN page about WebClient.UploadValues method and also NameValueCollection class. The page said that NULL value are accepted. How to POST null value? Is NULL value is unacceptable in this case?


Solution

  • The HTTP protocol is a textual protocol and therefore you can't really send a "null" value.

    Assuming you're using the JSON.net library (though there's probably equivalent ways to do this built-in).

    using (WebClient client = new WebClient())
    {
        var values = new Dictionary<string,object> { { "menu_parent",null } }; 
        var parameterJson = JsonConvert.SerializeObject(values);
        client.Headers.Add("Content-Type", "application/json"); 
    
        string URL = "http://192.168.20.152/test.php";
        byte[] response = client.UploadData(URL, Encoding.UTF8.GetBytes(parameterJson));
    
        string responseString = Encoding.Default.GetString(response);
    
        MessageBox.Show(responseString);
    }
    

    Then in PHP you can do:

    $data = json_decode(file_get_contents('php://input'));
    if ($data->menu_parent === null) {
       //should work
    }