Frage

Below is my php code which works fine:

<?php

//This script checks the id and code of the already registered user from the database. If correct it returns the other details otherwise the respective error

//starting session
session_start();

//catching data from client
$id=$_POST['id'];
$code=$_POST['code'];

if($id&&$code)//checking if the data is not empty
{
    //Connecting to server
    ($connect=mysqli_connect('localhost','root','','ohhell')) or exit("Connection Failed");

    //Selecting user for given id
    $result=mysqli_query($connect,"SELECT * FROM users WHERE id='$id'");

    //Counting number of rows
    $numrows=mysqli_num_rows($result);

    if($numrows!=0)
    {
        //Creating associative array
        $row=mysqli_fetch_assoc($result);

        //freeing result set
        mysqli_free_result($result);

        //fetching code from database
        $db_code=$row['code'];
        $code=md5($code);

        //checking if the codes match
        if($code==$db_code)
        {
            //change status
            mysqli_query($connect,"UPDATE users SET status='yellow' WHERE id='$id'");

            $_SESSION['id']=$row['id'];
            $_SESSION['name']=$row['name'];
            $_SESSION['location']=$row['location'];

            $name=$row['name'];
            $location=$row['location'];

            //closing connection
            mysqli_close($connect);

            //returning values to client
            exit("$name\n$location");//Successful Login. Client can now create an object and switch the screen
        }
        else
        {
            exit("Invalid Player Code");//Unsuccessful Login
        }
    }
    else
        exit("Invalid Player ID");//Unsuccessful Login
}
else
    exit("Incomplete Details");//Unsuccessful Login     

?>

It returns the respective error message or the corresponding details of the player to the c# client. Below is the client side code to receive the data:

WebRequest request = WebRequest.Create(URL);
Stream dataStream;
WebResponse response;
StreamReader reader;

response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();

After receiving the data successfully the c# client separates both the data with the help of "\n" and then makes an object of a class and fill the received data to the respective data members of that class.

Now here comes the problem, since I am testing now everything is working fine. But, my question is that, as the data being read is going to be in the form of string, how can I make sure at the client side that the data is actually received successfully and the string that is retrieved actually contains the data and not the error message.

I mean suppose if an internal error occurs while connecting to php or any other network error returns the corresponding error that too would be in the form of string, now how I am going to differentiate that whether the the client app should start separating the data from the string to make the object or it should terminate with an error. For the errors that I have included in my php I can use respective if() conditions in the c# client but that's not a proper way as the errors are not guaranteed to be limited to the considered errors in the php script. There might be a numerous number of errors that can be returned so what approach should be taken in this case to actually differentiate between the error and real data.

On possible approach is to prepend a signal say "1" to the data before sending it and to test for the signal at the client's side whether the received string starts with a "1". If yes then going for the separation else displaying the corresponding error message. But this approach is also not optimal as in the case the if the error itself starts with 1, it will fail.

So what should be actually done to send data to c# in an optimal way through a php script?

Sorry for the long description! Waiting for assistance!!!

Thanks a million billion trillion...:)

War es hilfreich?

Lösung

You could use http status codes to indicate error conditions. It seems currently you're only using 200 OK (by default), but e.g. Invalid Player Code could result in a 401 Unauthorized or 403 Forbidden (if that's meant for some kind of authorization).

On the c# side you'd get that status code via the HttpWebResponse.StatusCode property

Andere Tipps

You can use HTTP Status codes to determine weather or not an error occured. You php could set the respective HTTP header if an error occurs during the run of said php script i.e. using http_response_code. If the Startus code is okay, you can parse the response (as said in the comments, using json) and retrieve the results. In case an error occured in the network communication, you produce the respective error yourself in the client. If an error occured in PHP, you retrieve the error by also parsing the response, thereby retrieving the error message.

Simple Example in PHP

$response = array();
$responseCode = null;
try {
  // some code is executed
  $responseCode = 200;
}
catch (Exception $e) {
  // an error occured and we have to add it to our response
  $response['error'] = array('errorcode' => $e->getCode(), 'error' => $e->getMessage());
  $responseCode = 500;
}

http_response_code($responseCode);
echo(json_encode($response ));

Now in your c#, simply check the header. If it is 500 (meaning an error occured), json_decode the result and get the error. If it is 200 (meaning OK), json_encode the result. If it is anything else, responde to it according to the linkes HTTP Error Code list.

I refer to the comment-question of Vikas Prasad: "@ReeCube can I achieve all my requirements for the program trying JSON or XML. If yes can you point me to specific tutorials. I have no idea about these two. Also which one to prefer among both?"

JSON or XML are just the way how you transfer the data and how you read them after, you need php and c# to use JSON or XML. I prefer JSON but im not sure how well it's working on C#, I've never tested it.

Here you can find an JSON API for C#.

But first you should add JSON for your PHP-server. On PHP, JSON is very easy to use, there is an json_encode and json_decode function. In your case, you just need the json_encode function, because on the server side, you just want to generate the JSON for the client. How to use json_encode is very well supported by Google and the PHP documentation, but if you have questions, just ask in a comment.

Here is a little example:

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top