PHP and C#communication error

Asked

Viewed 79 times

1

I’m trying to send a C# data to PHP, but the example I find and all solutions simply result in the same error.

 using System.Net;
 using System.Collections.Specialized;

        string valor = "1";

        string urlAddress = "http://localhost:80/Untitled-1.php";

        using (WebClient client = new WebClient())
        {

            NameValueCollection postData = new NameValueCollection()
   {
          { "valor", valor}

   };


            client.UploadValues(urlAddress, postData);

        }

PHP code to receive data:

<html>

<?php
      $valor = $_POST["valor"];  

echo $valor;
 ?>

Error in PHP:

Notice: Undefined index: value in C: xampp htdocs Untitled-1.php on line 4

It’s a very simple code, but it’s the basis of a larger program. Does anyone have any idea what it might be?

  • Good evening, It may be that your php is not giving permission for external reading... Try assigning this at the top of your file: <?php header('Access-Control-Allow-Origin:*'); ? > Questions, I’m available.

  • Try to give a var_dump($_POST), if you do not give any value, it may be that your application c# is having some problem.

1 answer

1

I’m not sure, but I believe it’s for lack of defining the Content-Type of the request, thus:

using System.Net;
using System.Collections.Specialized;

string valor = "1";

string urlAddress = "http://localhost:80/Untitled-1.php";

using (WebClient client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

    NameValueCollection postData = new NameValueCollection()
    {
         { "valor", valor }
    };

    client.UploadValues(urlAddress, postData);
}

This problem has nothing to do with Access-Control-Allow-Origin: *, the WebClient is not a site trying to access another, is a customer trying to access a site, so there is no cross-origin. Apply the header('Access-Control-Allow-Origin: *'); in PHP does not solve anything and even if it was a problem related to CORS you could not even get the error generated in PHP.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.