如何使用 php web 服务成功登录
Posted
技术标签:
【中文标题】如何使用 php web 服务成功登录【英文标题】:How to successfully login using by php web service 【发布时间】:2016-08-16 06:12:17 【问题描述】:首先我有两个文本字段,第一个是登录,第二个是密码和一个登录按钮。我正在使用故事板和登录按钮,通过 push segue 连接到另一个视图控制器。这次在我的项目中工作,将用户名和密码放入文本字段并选择登录按钮并在控制台中打印服务器响应。 我想在移动另一个视图后成功登录并且登录失败不要移动另一个视图。
我的php代码
<?php
header('Content-type: application/json');
include('../conn.php');
if($_POST)
$loginid = $_POST['loginid'];
$loginpassword = $_POST['loginpassword'];
$schoolid = substr_id($loginid);
$table = tb3($schoolid);//profile
$sql=mysql_query("select * from $table where ID = '".$loginid."' AND PASSWORD = '".$loginpassword."'",$conn);
$row=mysql_fetch_assoc($sql);
if(mysql_num_rows($sql)>0)
echo '"success":1';
else
echo '"success":0,"error_message":"UserID and/or password is invalid."';
else
echo '"success":0,"error_message":"UserID and/or password is invalid."';
我的视图控制器代码
- (IBAction)Login:(id)sender
if([[self.user_id text] isEqualToString:@""] || [[self.password text] isEqualToString:@""] )
else
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:@"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:@"loginid=%@&loginpassword=%@&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(@"the data Details is =%@", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(@"got response==%@", resSrt);
if(resSrt)
NSLog(@"got response");
else
NSLog(@"faield to connect");
【问题讨论】:
我想在移动另一个视图后登录成功,登录失败不要移动另一个视图。` --> ? @Anbu.Karthik 移动到另一个视图,意思是“单击登录按钮并通过推动 segue 移动到主视图控制器” 如果你去哪里失败就OK 如果失败警报显示“登录失败” 好的,让我们解释一下你击中的地方 【参考方案1】:这一行是错误的
NSString *userUpdate =[NSString stringWithFormat:@"loginid=%@&loginpassword=%@&",_user_id.text,_password.text, nil];
您在参数中额外添加了
&
,这不在 loginpassword=%@& 中,您需要像 loginpassword=%@ 一样调用删除和发送请求
像这样使用
NSString *userUpdate =[NSString stringWithFormat:@"loginid=%@&loginpassword=%@",_user_id.text,_password.text, nil];
问题是您没有对 JSON 进行 serlize
所以删除NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
中的这一行
我听从你的回答
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[@"success"] integerValue];
if(success == 1)
NSLog(@"Login SUCCESS");
[self performSegueWithIdentifier:@"login_success" sender:self];
else
NSString *error_msg = (NSString *) jsonData[@"error_message"];
[self alertStatus:error_msg :@"Sign in Failed!" :0];
【讨论】:
如果你需要修改我在这里问 dropbox.com/s/xgd474if5vrjp5s/EduTime.zip?dl=0请查收 @AnkurKumawat - 你能提供示例用户 ID 密码吗 用户 id- 1000710017 , pwd- XM0MB @这里我成功了兄弟,添加我的答案你得到输出【参考方案2】:Ankur kumawat 我在 iOS 9 中尝试了你的编码和 @Anbu.karthik 兄弟的答案。我收到的警告很少。首先我发布了 Anbu.Karthik 兄弟的答案。
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:@"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *strUserId = @"1000710017";
NSString *strPassword = @"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:@"loginid=%@&loginpassword=%@",strUserId,strPassword, nil];
//Check The Value what we passed
NSLog(@"the data Details is =%@", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[@"success"] integerValue];
if(success == 1)
NSLog(@"Login SUCCESS");
[self performSegueWithIdentifier:@"login_success" sender:self];
else
NSString *error_msg = (NSString *) jsonData[@"error_message"];
[self alertStatus:error_msg :@"Sign in Failed!" :0];
上面是Anbu.Karthik兄弟的回答。我试过了,它显示了警告。
警告是
'sendSynchronousRequest:returningResponse:error:' 已弃用:首先 在 iOS 9.0 中已弃用 - 使用 [NSURLSession dataTaskWithRequest:completionHandler:](参见 NSURLSession.h
然后
隐式转换丢失整数精度:'long _Nullable' 到 'int'
当我收到警告时,我想删除警告和
我必须使用 NSURLSession 与 dataTask 因为 sendSynchronousRequest:returningResponse:error:' 在 iOS 9.0 中已弃用
然后我修改了代码。
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://sixthsenseit.com/school/project/ios/login.php"]];
NSString *strUserId = @"1000710017";
NSString *strPassword = @"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:@"loginid=%@&loginpassword=%@",strUserId,strPassword, nil];
//create the Method "GET" or "POST"
[urlRequest setHTTPMethod:@"POST"];
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[urlRequest setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(@"The response is - %@",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:@"success"] integerValue];
if(success == 1)
NSLog(@"Login SUCCESS");
else
NSLog(@"Login FAILURE");
else
NSLog(@"Error");
];
[dataTask resume];
打印出来的结果是
The response is -
success = 1;
和
Login SUCCESS
现在我的代码可以完美运行了:-)
【讨论】:
【参考方案3】:在视图控制器文件中试试这个代码:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSLog(@"%@",dict);
if (dict)
NSString *status = [NSString stringWithFormat:@"%@",[dict valueForKey:@"success"]];
output: 1 // successfully
or
0 // Unsccssfully
NSString *msg = [NSString stringWithFormat:@"%@",[dict valueForKey:@"error_message"]];
【讨论】:
【参考方案4】:用这个替换你的代码:
- (IBAction)Login:(id)sender
if([[self.user_id text] isEqualToString:@""] || [[self.password text] isEqualToString:@""] )
else
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:@"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:@"loginid=%@&loginpassword=%@&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(@"the data Details is =%@", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
Dictionary *dictResponce = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if (dictResponce)
NSString *status = [NSString stringWithFormat:@"%@",[dict valueForKey:@"success"]];
if (status == "1")
//Push to home view controller
[self performSegueWithIdentifier:@"Home_page" sender:self];
else
NSLog([NSString stringWithFormat:@"%@",[dict valueForKey:@"error_message"]]);
else
NSLog(@"faield to connect");
【讨论】:
以上是关于如何使用 php web 服务成功登录的主要内容,如果未能解决你的问题,请参考以下文章
如何使用ajax和jquery从php Web服务返回简单文本[重复]
如何使用使用自定义用户名验证和 PHP 页面的 WCF Web 服务?