这段代码有什么问题,我正试图进入我打开的MAMP服务器,我在服务器中有一个php文件,我正在测试连接等等,这个:
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
echo $username
echo $password
if($username && $password) {
$db_name = 'DBTest';
$db_user = 'pedro';
$db_password = 'pedro';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
在Xcode中,应用程序目前在swift中有3个视图,但重要的是:
//
// LogInViewController.swift
// ParkingApp
//
// Created by Pedro Alonso on 02/06/15.
// Copyright (c) 2015 Pedro Alonso. All rights reserved.
//
import UIKit
class LogInViewController: UIViewController {
@IBOutlet weak var loginLabel: UILabel!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func enterTapped(sender: UIButton) {
var username: String = usernameField.text
var password: String = passwordField.text
if ( username.isEmpty || password.isEmpty) {
var alertView: UIAlertView = UIAlertView()
alertView.title = "Failed"
alertView.message = "Error in the username or password"
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
} else {
var post: String = "username=\(username)&password=\(password)"
NSLog("Post data: %@", post)
println(post)
var url: NSURL = NSURL(string: "http://localhost:8888/jsonlogin2.php")!
var postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)!
var postLenght: String = String(postData.length)
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLenght, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var responseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
if urlData != nil {
let res = response as! NSHTTPURLResponse!
println(urlData)
NSLog("Response code: %ld", res.statusCode)
if (res.statusCode >= 200 && res.statusCode < 300) {
var responseData: NSString = NSString(data: urlData!, encoding: NSUTF8StringEncoding)!
NSLog("Response: ==> %@", responseData)
var error: NSError?
let jsonData: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
let succes: Int = jsonData.valueForKey("succes") as! Int
if succes == 1 {
NSLog("Login Success")
var prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(username, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var errorMsg: String?
if jsonData["error_message"] as? String != nil {
errorMsg = jsonData["error_message"] as! String?
} else {
errorMsg = "Unknown error"
}
var alertView: UIAlertView = UIAlertView()
alertView.title = "Sign in failed"
alertView.message = errorMsg
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = responseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
}
.php文件在/ Applications / MAMP / htdocs中,不清楚的是为什么给我回复代码500,而我不知道为什么会发生这种情况。任何帮助?感谢。
编辑:回复:
<NSHTTPURLResponse: 0x7fc42149ac60> { URL: http://localhost:8888/jsonlogin2.php } { status code: 500, headers {
Connection = close;
"Content-Length" = 0;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Thu, 04 Jun 2015 12:11:35 GMT";
Server = "Apache/2.2.29 (Unix) mod_wsgi/3.4 Python/2.7.8 PHP/5.6.7 mod_ssl/2.2.29 OpenSSL/0.9.8zd DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.8 Perl/v5.20.0";
"X-Powered-By" = "PHP/5.6.7";
} }
我可以从模拟器中的safari访问localhost:8888,因此没有连接问题。
EDIT2:显然是请求,因为它告诉我跳过所有的无效数据并返回此信息:
2015-06-04 17:16:11.914 ParkingApp[3777:126598] Response: ==> {"success":0,"error_message":"Invalid Data."}
我完成请求的方式可能有什么问题?
EDIT2:我已经更改了代码并激活了mysql日志以查看查询,但仍然是$ stmt-&gt; get_result()或fetch()无所事事,我不知道为什么。我不是在整个IOS中做到这一点,但这里简单的浏览器是麻烦的部分。
修改部分:
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$query = "SELECT dataOne,password FROM users WHERE username = ? and password = ?";
if ($stmt = $mysqli->prepare($query)) {
//$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
//$stmt->debugDumpParams();
echo $stmt->sqlstate;
var_dump($stmt);
/* bind result variables */
//$stmt->bind_result($dataOne,$password);
$result = $stmt->get_result();
printf("test: ", $dataOne, $password);
//fetch value
while($stmt->fetch()) {
echo $dataOne;
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($result != null) {
error_log("User $username: password match.");
echo '{"success":1, "dataOne:"'.$dataOne.'}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
$ stmt没有重新调整get_result()上的任何内容,或者没有进入while(fetch())我现在还不知道。有什么帮助吗?
答案 0 :(得分:1)
好吧,如果您的Web服务器丢失了http错误代码500(内部错误),那是因为您的PHP脚本崩溃了。我会尝试阅读php日志,并尝试对php脚本进行一些调试。
也许您的iOS应用中发布的数据有问题,导致php脚本失败?
在这种情况下,从safari访问localhost:8888并不能证明php脚本正常工作,因为它要求您发布脚本执行的任何数据。 if($_POST) {
。只需浏览该脚本,if语句永远不会是true
。
编辑:
有时候有助于一次验证一个组件。尝试构建一个简单的html表单,针对您的服务器(username
)发布password
和http://localhost:8888/jsonlogin2.php
。当您看到此按预期工作时,请继续确保该应用有效。这样,您可以判断您的错误是在服务器(PHP脚本)上还是在您的应用程序中。
最好像这样检查$_POST
:
if (!empty($_POST)) {}
这将检查$_POST
是否为空。
您的应用也在使用application/x-form-urlencoded
,我猜这应该是:application/x-www-form-urlencoded
。
但又一次。制作一个本地html表单,并确保您的PHP脚本正常工作,然后转移到该应用程序。