Sending a request to a php web service from iOS - php

I have a question relating to sending a POST request from an iOS app to a web service written in php, that will ultimately query a MySQL database.
tldr: How do I view the contents of the POST variables directly in the browser window, without refreshing?
Long version:
I had written my Swift code in Xcode, with NSURLSession, request, data etc.
I had a php web page set to var_dump($_POST); so that I could check that the data was sent in correctly (my data was a hard-coded string in Xcode for testing purposes).
I couldn't for the life of me figure out why I kept getting empty POST variables, until I decided to add a test query statement to my web page binding the POST variable. Lo and behold, the query ran successfully and my table updated.
I now realise that the reason I thought the POST variable was empty was because I was refreshing the web page in order to see the results of my var_dump. I now also know that this was deleting the POST data, because when I repeated this action with the query statement, my table was getting NULL rows.
My question is how do I view the contents of the POST variables directly in the browser window, without refreshing? I know this must be a real noob goose chase I've led myself on... but I am a noob.
Thank you

You would need to modify the service itself to output those values in some way. If this is strictly for debugging, you are better off having the service write out to a log file instead. If this is part of the requesting applications call and the data needs to be displayed to the user, the service should probably return either an XML or JSON string response that your application can parse. Otherwise, you can use Fiddler to monitor your web traffic.

Of course overtime you refresh the page you just get an empty variable.
This is what I used to test if my code was working:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
testPost() // this function will test that the code is sending the variable to your server
return true
}
func testPost() {
let variableToPost = "someVariable"
let myUrl = NSURL(string: "http://www.yourserver.com/api/v1.0/post.php")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "variable=\(variableToPost)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in
if error != nil {
print(error)
return
}
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json{
let result = parseJSON["status"] as? String
let message = parseJSON["message"] as? String
if result == "Success"{
//this should return your variable
print(message)
}else{
// print the message if it failed ie. Missing required field
print(message)
}
}//if parse
} catch let error as NSError {
print("error in registering: \(error)")
} //catch
}
task.resume()
}
then your php file will only check if there is no empty post and return the variable as JSON:
post.php
<?php
$postValue = htmlentities($_POST["variable"]);
if(empty($postValue))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
} else {
$returnValue["status"] = "success";
$returnValue["message"] = "your post value is ".$postValue."";
echo json_encode($returnValue);
}

Related

POST requests not working in Swift with Alamofire

I'm trying to send data from a Swift app to a backend in PHP.
To test, I make a request via POST with Alamofire and print the request method as a response from the Server.
let URL_USER = "myurl"
var sampleRequest = URLRequest(url: URL(string: URL_USER)!)
sampleRequest.httpMethod = HTTPMethod.post.rawValue
AF.request(sampleRequest).uploadProgress{ progress in }.response(){
response in
if(response.data != nil) {
print(String(bytes: response.data!, encoding: .utf8) as Any)
}
else {
print("Error")
}
}
The PHP script:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo 'OK';
}
else {
echo 'Wrong request method';
}
The server response is always Wrong request method
The same also occurs using the post parameter directly inside the Alamofire call, with this code:
AF.request("myurl", method: .post).response {...}
Any attempt to send the request via POST, even without Alamofire, fails and the server replies saying that the request is of type GET.
This occurs both on the simulator and on a real device, without any proxy.
The URL I call is based on https
UPDATE
To test the basic functioning of Alamofire with the function of their documentation I tried this code:
AF.request(URL_USER, method: .post).response {
response in
if(response.data != nil) {
print(String(bytes: response.data!, encoding: .utf8) as Any)
}
else {
print("Error")
}
}
But the response still goes Wrong request method and Proxyman says it's of type GET
The problem was caused by a redirect in the URL.
For some reason https://mysite.tld was redirecting to https://www.mysite.tld using GET. In this way all the parameters and the type of request were altered. I solved the problem by making the request directly to https://www.mysite.tld.
To find out the redirect I used Proxyman.

Stripe Alamofire response looks like array with elements separated by a semicolon

I am making an Alamofire request but getting an odd response. (Swift 3)
Alamofire.request(url, parameters: params).validate(statusCode: 200..<300).responseJSON { response in
if let result = response.result.value {
let JSON = result as! NSDictionary
print("JSON: \(JSON)")
}
This prints the following:
JSON: {
message = "Payment has been charged";
status = Success;
}
Looks solid, but I'm having trouble with two pieces of this response. First off, what is the type of this response. Array? Any? Dictionary? Second, how would I access an element in it. For instance, I want to check to see if the status equals Success.
The last piece of information I have is that my backend (in PHP) produces this with:
$response = array("status"=>"Success","message"=>"Payment has been charged");
Thank you for any insight!

How to establish a connection to a web server with NSURL in which variables can be passed securely via URL to PHP script

I am using Swift's NSURL function to connect to a PHP script that I can use to interact with a MySQL database. Everything is running smoothly except for the insecurity of the variables passed in the URL via POST. If someone were to intercept these variables it would pose an enormous security risk to my application. I have researched the subject extensively however I have hit a wall. Is an SSL certificate enough to secure the URL? I am not passing the variables through the literal URL but a POST method. As far as I know, the SSL certificate provides security for the data passed AFTER the initial connection (meaning that the data originally passed via POST and the URL are not secure). So essentially, how do I go about passing variables to a web server securely?Here is the code I am using to establish the connection:
let myUrl = NSURL(string: "http://testsite.com/login.php”)
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = “username=bob&password=123"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
if let responseData = data {
let responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
}
}
} else {
self.sendAlert("Error", message: "Unable to establish connection")
}
}
You can refer to raywenderlich tutorials for setting up the iOS part of it. This tutorial is for connection between ruby rails and swift. It has sign in, sign up and token system, it also includes encryption.
The tutorial uses httpBody to pass the information, you can stick with that or modify to header instead to personalise your codes as required.
request.addValue("bob", forHTTPHeaderField: "username")
request.addValue("123", forHTTPHeaderField: "password") // add AES Encryption.
Also, you can implement a token system instead of passing your username and password. You would however have to pass it initially to get the token.

Start PHP with Swift

I wanted to send an email via a websever and php. Therefore I created a connection to my webserver (000webhoster).
Nearly everything works fine.
My main problem is, that I don't receive anything. I am not even sure, if the PHP code is even executed.
This is my current swift code:
func postToServer (){
print("button pressed")
var url: NSURL = NSURL(string: "http://www.bl1nd3d.herobo.com/email.php")!
var request: NSMutableURLRequest = NSMutableURLRequest(URL:url)
var bodyData = "data=something"
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ response, data, error in
if let HTTPResponse = response as? NSHTTPURLResponse {
let statusCode = HTTPResponse.statusCode
if statusCode == 200 {
print("nice")
// TODO : Sent successfully popup
}
else {
print(statusCode)
}
}
})
}
This works fine ^^ .. I always receive the statuscode of 200. (If you wanted to try this you need to enable the insecure AppTransport)
And this is my PHP code.. I believe this doesn't work that properly..
<?php
$postVar = $_POST['data'];
if (!empty($postVar)) {
echo $postVar;
// email , subject, message
mail("myMail#mail.com","Agent was booked","The POST was set and button was pressed" . $postVar);
}
echo "doesn't work that good " . $postVar;
?>
I checked, it should be possible with my webhoster, to send emails..
But it doesn't work.. Did I forget something?
Well something must have gone really bad wrong... My whole dir was deleted while trying this.. :O
The directory /public_html does not exist or could not be selected, so
the directory / is shown instead.
well it probably didn't work that well.. My account was blocked...
Did you check the spam folder? Standard mail() function is not a great solution to send emails. Your mail provider can block email's sent from mail() or it just couldn't work at all. You need to send mail using smtp. Here's the example

Swift: How to use NSURLSession to query external database?

I am writing this question because I am in a big difficulty in understanding how to implement a simple basic authentication login with Swift.
The first screen of my app is a simple form with text fields (username and password) and a Sign In button. In my LoginViewController.swift file I linked the button to this:
#IBAction func doLogin(sender : AnyObject) {
}
The probem now is that I don't know how to go on. I have a local server in MAMP where there is this file.php querying a database and which works perfectly:
<?php
$deep="";
require_once($deep."class/config.php");
$sistema = new config($deep);
if( isset($_GET["username"]) && isset($_GET["password"]) ) {
$username=mysqli_real_escape_string($sistema->dbConn,$_GET["username"]);
$password=mysqli_real_escape_string($sistema->dbConn,$_GET["password"]);
$userL=$sistema->user->allAdmin("WHERE username='".$username."' AND password='".$password."' ");
echo json_encode($userL);
}
?>
So how can I perform a GET request to this file? I suppose I need to create a URL with user data like this form:
http://localhost:8888/excogitoweb/loginM.php?username=lorenzo&password=lorenzo
but then I don't know how to go on. How can I perform this request to retrieve that JSON content? And how can I check that JSON content in order to understand if the sign in procedure has succeeded or has not?
I have watched many tutorials in youtube, overall this but even if I copy the code they show I always get compilation errors...
for a "normal" GET request you need a NSURLRequest with your url... Its just like this:
if let requestURL: NSURL = NSURL(string: "http://localhost:8888/excogitoweb/loginM.php?username=lorenzo&password=lorenzo") as NSURL? {
let urlRequest: NSURLRequest = NSURLRequest(URL: requestURL)
let urlSession = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if let responseJSON: [String: String] = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? [String: String] {
///Here you can handle the responded JSON
}
})
urlSession.resume()
}
Don't forget, you are on a background Task when you handle the responded JSON... If you want to do some UI Stuff there you will need to dispatch it to the mein queue
Also a would recommend you doing HTTP POST instead of HTTP GET for such things
UPDATE
if let responseJSON: [[String: String]] = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? [[String: String]] {
///Here you can handle the responded JSON
}

Categories