0

I'm creating a Swift POST Request to a MySQL web service after tapping in a button with some code. However, I am not getting the expected results that I need. Whenever I try to pass the $_POST variables to the php webservice, my mysqli_query inside always returns nothing with regards to my post variables.

I troubleshooted in both Swift and MySQL and these are the results I'm getting.

In Swift, using print:

["error": Invalid username and/or password., "password": <null>, "username": <null>, "allData": {
    "{\n__\"username\"_:_\"Test_User\",\n__\"password\"_:_\"testuser\"\n}" = "";
}]

As seen here, both password and username has null, but when I try to include all the post parameters on the json object I'm returning from the php webservice, it can be seen that I am passing it with the format that I'm not sure of (e.g. "allData": { "{\n__\"username\":\"Test_User\"), ...

This is currently my code on the view controller:

@IBAction func signinTapped(_ sender: Any) {

        // Read values from login text fields
        let loginUsrVar = loginUsr.text
        let loginPwdVar = loginPwd.text

        let urlPath = URL(string: "https://website.com/WebServices/CheckUser.php")
        var request = URLRequest(url: urlPath!)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "content/type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let postString = ["username": loginUsrVar!, "password": loginPwdVar!] as [String:String]

        let postString:NSDictionary = ["username": loginUsrVar!, "password": loginPwdVar!]
        print("postString:", postString)

        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
            print("JSON Serialization successful.")
            print(request)  
        } catch let error {
            print(error.localizedDescription)
            displayMessage(userMessage: "Something went wrong during the login process...")
            return
        }


        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

            if error != nil {
                self.displayMessage(userMessage: "Could not successfully perform  the request. Please try again later.")
                return
            }

            print("data sent:", data)
            print("successful response:", response)

            let dataTransformed = NSString(data: request.httpBody!, encoding:String.Encoding.utf8.rawValue)!

            print("response encoded:", dataTransformed)

            do {
                let jsonResult = try JSONSerialization.jsonObject(with: data!, options: [.mutableContainers]) as? NSDictionary
                if let jsonResult = jsonResult as? [String: Any] {
                    print(jsonResult)
                }
            } catch {
                self.displayMessage(userMessage: "Could not successfully perform this request. Please try again later.")
            }


        }
        task.resume()
    }

And I'm using a webservice to pull the data that I need for the app with this php code:

<?php
// header("Content-Type: application/json");
// Create connection
$con=mysqli_connect("database_address","username","password","current_app");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM users WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'";
// $sql = "SELECT * FROM users WHERE username='Test User 1' and password = 'testuser'";

// Check if there are results
  if ($result = mysqli_query($con, $sql))
  {
    $count = mysqli_num_rows($result);

    if ($count == 0 ) {                                                         // If no users are found with sql query
      // echo "Invalid username and/or password.";
      $msg -> error = "Invalid username and/or password.";
      $msg -> username = $_POST["username"];
      $msg -> password = $_POST["password"];
      $msg -> allData = $_POST;
      echo json_encode($msg, JSON_UNESCAPED_SLASHES);
      // echo $_POST["username"];
    } else {                                                             

      $msg -> greeting = "hello";
      $msg -> otherData = $_POST;

      echo json_encode($msg);
    }
  }

// Close connections
mysqli_close($con);
?>

My question is, how do I correctly pull the post variables for the webservice to use?

  • You are not reading the variables passed by the post in your PHP file. – El Tomato Mar 01 '19 at 01:19
  • You are sending JSON request, but your PHP is expecting `application/x-www-form-urlencoded` request. They’re two completely different things. – Rob Mar 01 '19 at 01:23
  • @El Tomato So, how do I read them correctly? I'm using $_POST["username"] and $_POST["password"] which should pull them. – Midnite Dev Mar 01 '19 at 01:24
  • Either change your PHP to parse JSON (e.g. https://stackoverflow.com/a/27884399/1271826) or create `application/x-www-form-urlencoded` request (e.g. https://stackoverflow.com/a/26365148/1271826) – Rob Mar 01 '19 at 01:25
  • By the way, either way, make sure you either use [`mysqli_real_escape_string`](http://php.net/manual/en/mysqli.real-escape-string.php) or bind values as shown in that first answer. Never just take user input and build SQL directly from that. Otherwise you’re susceptible to SQL injection attacks. https://www.xkcd.com/327/ – Rob Mar 01 '19 at 01:27
  • @Rob, thanks for the tip on sql injection protects. I implemented it as well as tried out adding request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") on Swift and also using json_decode() on my webservice separately to test whether either of these would help. It still does not show $_POST values. – Midnite Dev Mar 01 '19 at 02:44
  • It’s not just setting the content header to `application/x-www-form-urlencoded`, but have you retired all of that code that builds the body of the request with JSON, too. You have to do something like https://stackoverflow.com/questions/26364914/http-request-in-swift-with-post-method/26365148#26365148 – Rob Mar 01 '19 at 02:52

0 Answers0