I am trying to authenticate a user by sending a POST request from my iOS app to a php script. Then having the iOS app read the NSHTTPURLResponse to determine whether or not it was successful. My iOS code is shown below, for some reason it says that my NSURLConnection is unused. The int code always shoots back a value of 200.
- (void)authenticateUser:(NSString *)aUsername
password:(NSString *)aPassword
{
NSString *post = [NSString stringWithFormat:@"username=%@&pw=%@", aUsername, aPassword];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [post length]];
NSURL *url = [NSURL URLWithString:@"http://XXX.com/query-db.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = [httpResponse statusCode];
// Log the response
NSLog(@"%d", code);
if(code == 1){
NSLog(@"received a 1");
[self updateWorkTime];
//[self close];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unsuccessul Attempt" message:@"The username or password is invalid, please try again." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Additionally, if you want to take a look at my php script, which I entered in dummy variables for and tested to see if it queried the database properly and that checked out… But just in case you’re curious.
<?php
$sentUsername = $_POST['username'];
$sentPW = $_POST['pw'];
mysql_connect("xxx", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$result = mysql_query("SELECT * FROM Table") or die(mysql_error());
$authenticate = 0;
while($authenticate == 0) {
$row = mysql_fetch_array($result);
$selectedUsername = $row['username'];
$selectedPW = $row['pw'];
$pwComp = strcmp($sentPW, $selectedPW);
$userComp = strcmp($selectedUsername, $sentUsername);
if(!$row) break;
if($selectedPW == $sentPW && $selectedUsername == $sentUsername) {
$authenticate = 1;
}
}
echo $authenticate;
?>
I tried to set the PHP header, but I was unsure how to do that. I appreciate any and all help this community has given me, truly invaluable. Thanks!
The ‘200’ code you’re getting back is the HTTP status code, indicating that the request was successful.
If you’re after the ‘1’ or ‘0’ value being sent back from your PHP script, you should look for it in the
didReceiveData:delegate method, notdidReceiveResponse:.