NSHTTPURLRequest can't read statusCode - php

Just doing a normal HTTP post with a NSMutableURLRequest and sendAsynchronousRequest. But the NSHTTPURLResponse object I pass in has a statusCode of zero after the call. I get this error:
sendAsynchronousRequest error = Error Domain=NSURLErrorDomain
Code=-1005 "The network connection was lost." UserInfo=0xb374a00
{NSErrorFailingURLStringKey=http://54.221.224.251,
NSErrorFailingURLKey=http://54.221.224.251, NSLocalizedDescription=The
network connection was lost., NSUnderlyingError=0xb587990 "The network
connection was lost."} 2013-09-04 16:46:19.146 panic[2032:5907]
statusCode: 0
but no status code. Why? The status code the server is sending is 150.
When I POST different data to the server, and don't ask it to return a statusCode, the connection goes smoothly and as expected.
App Code:
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error)
NSLog(#"sendAsynchronousRequest error = %#", error);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:#"%d",code];
NSLog(#"%#",coder);
if (data) {
NSLog(#"This is Data: %#",data);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:#"%d",code];
NSLog(#"%#",coder);
}
}];
PHP Code:
index.php
<?php
require_once 'includes/main.php';
class dumb {
function dumber(){
/*--------------------------------------------------
Handle visits with a login token. If it is
valid, log the person in.
---------------------------------------------------*/
if(isset($_GET['tkn'])){
// Is this a valid login token?
$user = User::findByToken($_GET['tkn']);
if($user){
// Yes! Login the user and redirect to the protected page.
$user->login();
redirect('panic://success');
}
// Invalid token. Redirect back to the login form.
redirect('panic://fail');
}
/*--------------------------------------------------
Handle logging out of the system. The logout
link in protected.php leads here.
---------------------------------------------------*/
if(isset($_GET['logout'])){
$user = new User();
if($user->loggedIn()){
$user->logout();
}
redirect('index.php');
}
/*--------------------------------------------------
Don't show the login page to already
logged-in users.
---------------------------------------------------*/
$user = new User();
if($user->loggedIn()){
redirect('protected.php');
}
/*--------------------------------------------------
Handle submitting the login form via AJAX
---------------------------------------------------*/
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["phash"])){
rate_limit($_SERVER['REMOTE_ADDR']);
rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);
$message = '';
$name = $_POST["name"];
$email = $_POST["email"];
$phash = $_POST["phash"];
$subject = 'Your Login Link';
if(!User::exists($email)){
$subject = "Thank You for Registering!";
$message = "Thank you for registering at our site!\n\n";
// Attempt to login or register the person
$user = User::loginOrRegister($email, $name, $phash);
$message.= "You can login from this URL:\n";
$message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";
$message.= "The link is going expire automatically after 10 minutes.";
$result = send_email($fromEmail, $_POST['email'], $subject, $message);
if(!$result){
sendResponse(403, 'Error Sending Email');
return false;
}
}
else{
sendResponse(150, 'Account already created.');
return false;
}
}
else if(isset($_POST["email"]) && isset($_POST["phash"])){
rate_limit($_SERVER['REMOTE_ADDR']);
rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);
$message = '';
$name = '';
$email = $_POST["email"];
$phash = $_POST["phash"];
$subject = 'Your Login Link';
if(!User::exists($email)){
sendResponse(155, 'Account not yet created.');
return false;
}
else{
// Attempt to login or register the person
$user = User::loginOrRegister($email, $name, $phash);
$message.= "You can login from this URL:\n";
$message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";
$message.= "The link is going expire automatically after 10 minutes.";
$result = send_email($fromEmail, $_POST['email'], $subject, $message);
if(!$result){
sendResponse(403, 'Error Sending Email');
return false;
}
}
}
/*--------------------------------------------------
Output the login form
---------------------------------------------------*/
}
}
$api = new dumb;
$api->dumber();
?>
sendResponse function
function sendResponse($status, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . 'ERROR';
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}

1xx status codes are special (see http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p2-semantics-23.html#status.1xx); also, it's not a good idea just to make up new status codes.

Related

Not response from server in JSON request

I am working on a login system for an iOS app.
I am now testing the response from remote server.
This is the function for the LOGIN button in the app:
#IBAction func btnEntrar(_ sender: Any) {
let correo = txtEmail.text!
let pass = txtPassword.text!
if(correo == "" || pass == ""){
print("campos vacios")
return
}
let postString = "email=\(correo)&password=\(pass)"
print("envar solicitud \(postString)")
let url = URL(string: "http://.../login.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"//tipo de envio -> metodo post
request.httpBody = postString.data(using: .utf8)// concatenar mis variables con codificacion utf8
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {//si existe un error se termina la funcion
self.errorLabel.text = "error del servidor";
print("solicitud fallida \(String(describing: error))")//manejamos el error
return //rompemos el bloque de codigo
}
do {//creamos nuestro objeto json
print("recibimos respuesta")
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {
DispatchQueue.main.async {//proceso principal
let mensaje = json["mensaje"]//constante
let mensaje_error = json["error_msg"]//constante
let error_int = Int(json["error_msg"]!)//constante
print("respuesta: \(mensaje_error ?? "sin mensaje")")
}
}
} catch let parseError {//manejamos el error
print("error al parsear: \(parseError)")
self.errorLabel.text = "error del servidor (json)";
let responseString = String(data: data, encoding: .utf8)
print("respuesta : \(String(describing: responseString))")
}
}
task.resume()
}
And this the PHP file that is receiving the request.
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['email']) && isset($_POST['password'])) {
// receiving the post params
$email = $_POST['email'];
$password = $_POST['password'];
// get the user by email and password
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
$response["user"]["imagen"] = $user["imagen"];
$response["user"]["nombre"] = $user["nombre"];
$response["user"]["apellidos"] = $user["apellidos"];
$response["user"]["nivel_usuario"] = $user["nivel_usuario"];
$response["user"]["unidad"] = $user["unidad"];
$response["user"]["id_usuario"] = $user["id_usuario"];
echo json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Wrong credentials! Please, try again!";
echo json_encode($response);
}
} else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters email or password is missing!";
echo json_encode($response);
}
?>
I am not getting any error or exception, but the last output I receive is
print("recibimos respuesta")
Am I doing something wrong?
EDIT
Demo JSON output
{"error":true,"error_msg":"Required parameters email or password is missing!"}
Your response Object contains not only String. It contains Bool also. You could use like below,
if let json = try JSONSerialization.jsonObject(with: data) as? [String:Any] { //Any for, Any data type
//Do with json
print(json)
}
I think you need to add content type header to the request like this (Objective-C):
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];

Xcode 8 Swift 3.0 : Parse error - Could not read PHPMailer code

I have a problem on xcode 8.
In PHP, I'm using PHPMailer to send the email. my PHP code like below.
send.php
<?php
require 'database/connect.php';
global $connect;
date_default_timezone_set('Etc/UTC');
require 'PHPMailer-master2/PHPMailerAutoload.php';
if ( isset($_POST['data1']) && isset($_POST['data2']))
{
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
$sql = "SELECT * FROM table WHERE data1 = '$data1' AND data2='$data2'";
$result = mysqli_query($connect, $sql);
if ($result && mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result)){
}
$output = array('message' => '1');
echo json_encode($output);
$add = "INSERT INTO table (data1, data2)
VALUES ('$data1','$data2')
";
$run = mysqli_query($connect,$add);
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'gmail.com';
$mail->Password = '******';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('sender#mail.com', 'sender');
$mail->addAddress('receiver#mail.com','receiver');
$mail->isHTML(true);
$mail->Subject = 'Test';
$mail->Body = 'Test';
$mail->AltBody = 'Test';
if(!$mail->send()) {
echo json_encode([
'status' => false,
'message' => 'Message could not be sent. Error: ' . $mail->ErrorInfo
]);
} else {
$status = array();
$status[] = array('status' => '1');
}
$output = array('message' => '1', 'status' => $status);
echo json_encode($output);
exit();
// End sending email
exit();
mysqli_free_result($result);
}
else {}
}
?>
I managed to send the data to the server and send email to receiver using code above.
The only issue I'm facing right now is in xcode. It says:
Parse error: The data couldn’t be read because it isn’t in the correct
format.
Xcode can't read my PHPMailer code in PHP file, that cause my swift 3.0 code to execute an Catch statement instead of message == '1' statement. My swift code as below.
post.swift
#IBAction func sendApplyMovement(_ sender: Any) {
let url = URL(string: "http://localhost/send.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let valueToSend = "data1=&data2"
request.httpBody = valueToSend.data(using: String.Encoding.utf8)
let myAlert = UIAlertController(title: "Confirm", message: "Sure ?", preferredStyle: UIAlertControllerStyle.alert)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil)
let okaction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler:
{
action in
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if error != nil {
return
}
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
DispatchQueue.main.async {
let message = Int(json["message"]!)
let status = Int(json["status"]!)
if(message == 1){
if(status == 1){
print("Success")
let myViewController:ViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let navigationController = UINavigationController.init(rootViewController: myViewController)
appDelegate.window?.rootViewController = navigationController
appDelegate.window?.makeKeyAndVisible()
let myAlert = UIAlertController(title: "Success!", message: "Sent !", preferredStyle: UIAlertControllerStyle.alert)
myAlert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
navigationController.present(myAlert, animated: true, completion: nil)
return
}
}
else {return}
}
}
}
catch let parseError { print("Parse error: \(parseError.localizedDescription)") }
}
})
task.resume()
}
)
myAlert.addAction(okaction)
myAlert.addAction(cancel)
self.present(myAlert, animated: true, completion: nil)
}
}
Is there something that I need to modify in order to make it work?
You're doing this:
if let json = try JSONSerialization.jsonObject(with: data!)
This implies that the data you're getting is in JSON format, but your PHPMailer code does this:
if(!$mail->send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
echo 'Message has been sent';
}
which does not return JSON code, so I'm not surprised you're having trouble parsing it. You posted this question before but it was very unclear - you made it sound like Xcode couldn't open your PHP file, not that you couldn't parse a response; it's a Swift runtime error, not an Xcode error.
Return your response in JSON format and you might have more success, something like:
if(!$mail->send()) {
echo json_encode([
'status' => false,
'message' => 'Message could not be sent. Error: ' . $mail->ErrorInfo
]);
} else {
echo json_encode([
'status' => true,
'message' => 'Message sent'
]);
}

using POST to store user information in web server IOS app

I'm building an IOS app using Swift + xcode7 + php scripts + mysql server side (Bluehost) it is actually my first project using xcode
When I try to store user information into the database nothing happened and no error messages appear plus there is no row added.
Here is my code , I tried to inspect it but nothing seems to be wrong.
// send user data to a server side
let myUrl = NSURL(string: "http://thetogo.net/userRegister.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "email=\(userEmail)&password=\(userPassword)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data,response, error in
if error != nil {
print("error=\(error)")
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json{
let resultValue = parseJSON["status"] as? String
print("result: \(resultValue)")
var isUserRegistered:Bool = false;
if(resultValue=="Success") { isUserRegistered = true; }
var messageToDisplay:String = parseJSON["message"] as! String!;
if(!isUserRegistered){
messageToDisplay = parseJSON["message"] as! String!;
}
dispatch_async(dispatch_get_main_queue(), {
//DisplayAlertMessage with confirmation
let myAlert = UIAlertController(title: "Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "Ok", style:UIAlertActionStyle.Default){ action in
self.dismissViewControllerAnimated(true, completion: nil);
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated:true, completion: nil);
});
}} catch {
print(error)
}
}
And this is my php code
<?php
require("Conn.php");
require("MySQLDao.php");
$email = htmlentities($_POST["email"]);
$password = htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetails($email);
if(!empty($userDetails))
{
$returnValue["status"] = "error";
$returnValue["message"] = "User already exists";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password); // I do this, so that user password cannot be read even by me
$result = $dao->registerUser($email,$secure_password);
if($result)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($returnValue);
return;
}
$dao->closeConnection();
?>
1.) Write below code in your php code to check errors :
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'on');
2.) Use $_GET http method and hit url directly on browser.
After doing this you will see what error you are facing. After solving
error just replace $_GET to $_POST

How to access my server MySql from IOS simulator to retrieve data swift

What could be wrong with this code, I'm trying to get into my MAMP sever which is turned on, I have one php file in the server where I'm testing the connections and such, this:
<?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."}';
}
?>
And in Xcode The app currently has 3 views all in swift, but the important one is this:
//
// 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()
}
}
}
}
The .php file is in /Applications/MAMP/htdocs, what is not clear is why is giving me response code 500, and I'm at a lost not sure why is happening. Any help?? Thanks.
EDIT: The response:
<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";
} }
I can access from safari in the simulator to localhost:8888, so there is no connection problem.
EDIT2: So it is the request apparently, because it tells me invalid data skipping all and returning this:
2015-06-04 17:16:11.914 ParkingApp[3777:126598] Response: ==> {"success":0,"error_message":"Invalid Data."}
What could be wrong with the way I've done the request?
EDIT2: I have changed the code and activated the mysql log to see the queries, but still the $stmt->get_result() or fetch() are doing nothing and I do not know why. I'm not doing it throughout IOS but simple browser here is the troublesome part.
Modified part:
$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"}';
}
}
The $stmt is not retuning anything on the get_result() or is not going into the while(fetch()) I'm just do not know now. Any help?
Well, if your web server is throwing http error code 500 (Internal Error) it is because your PHP script is crashing. I would try and read the php log, and try and do some debugging of the php script.
Maybe there is something wrong with the posted data from your iOS app, making the php script fail?
Also accessing localhost:8888 from safari in this case would not prove that the php script is working, as it requires you to post any data for the script to execute. if($_POST) {. By just browsing that script, the if statement will never be true.
EDIT:
It some times helps to verify one component at a time. Try building a simple html form that posts username and password against your server (http://localhost:8888/jsonlogin2.php). When you see this working as expected, move on to making sure the app works. This way you can tell if your errors are on the server (php script) or in your app.
It's also good to check $_POST like this:
if (!empty($_POST)) {}
This will check if the $_POSTis empty.
Your app is also using application/x-form-urlencoded and my guess is that this should be: application/x-www-form-urlencoded.
But once again. Make a local html form, and make certain that your php script is working, and then move over to the app.

ASIHTTPRequest and PHP Status Code always returns 200 or 500

My problem is that the php responseStatusCodes are not showing up on iOS. No matter what status code I return in sendResponse(), when reading the responseStatusCode in iOS, I get the output 500. Why is this and how can I fix it? Im assuming this is an error with PHP and has nothing to do with ASIHTTPRequest. But just for good measure, I've included the code used on the iOS side.
Let me know if their is any other code you need to help assist me.
Thanks in advance!
Here is the code I use to start a connection to the server.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.shouldAttemptPersistentConnection = NO;
[request setPostValue:name forKey:#"name"];
[request setPostValue:email forKey:#"email"];
[request setPostValue:phash forKey:#"phash"];
[request setDelegate:self];
[request startAsynchronous];
This is the code that I run when receiving a request finished message.
/
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Request Finished");
int statusCode = [request responseStatusCode];
if (statusCode == 150) {
NSLog(#"User Already Registered.");
} else if (statusCode == 155){
NSLog(#"User Not Registered");
} else if (statusCode == 403) {
NSLog(#"Tester 2");
} else if (statusCode == 200) {
if (registering == true){
[UIView animateWithDuration:1.0 animations:^{
_wheel.alpha = 0.0;
}];
[UIView animateWithDuration:1.0 delay:1.0 options:0 animations:^{
_clickToRegister.alpha=1.0;
}completion:nil];
} else {
[UIView animateWithDuration:1.0 animations:^{
_wheel.alpha = 0.0;
}];
[UIView animateWithDuration:1.0 delay:1.0 options:0 animations:^{
_clickToLogin.alpha=1.0;
}completion:nil];
}
NSLog(#"Tester 3");
} else if (statusCode > 1 && statusCode < 1000){
NSLog(#"Test Worked");
NSLog(#"%d",statusCode);
} else {
NSLog(#"%d",statusCode);
NSLog(#"Tester 4");
}
}
Here is the PHP Code that is supposed to send a responseStatusCode.
function sendResponse($status, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . 'error';
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}
And here is the code that calls this function.
sendResponse(503, 'User not Registered');
return false;
Here is the code for the entire file with the sendResponse call in it.
<?php
require_once 'includes/main.php';
class dumb {
function dumber(){
echo "Hello, PHP!";
/*--------------------------------------------------
Handle visits with a login token. If it is
valid, log the person in.
---------------------------------------------------*/
if(isset($_GET['tkn'])){
// Is this a valid login token?
$user = User::findByToken($_GET['tkn']);
if($user){
// Yes! Login the user and redirect to the protected page.
$user->login();
redirect('panic://success');
}
// Invalid token. Redirect back to the login form.
redirect('panic://fail');
}
/*--------------------------------------------------
Handle logging out of the system. The logout
link in protected.php leads here.
---------------------------------------------------*/
if(isset($_GET['logout'])){
$user = new User();
if($user->loggedIn()){
$user->logout();
}
redirect('index.php');
}
/*--------------------------------------------------
Don't show the login page to already
logged-in users.
---------------------------------------------------*/
$user = new User();
if($user->loggedIn()){
redirect('protected.php');
}
/*--------------------------------------------------
Handle submitting the login form via AJAX
---------------------------------------------------*/
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["phash"])){
rate_limit($_SERVER['REMOTE_ADDR']);
rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);
$message = '';
$name = $_POST["name"];
$email = $_POST["email"];
$phash = $_POST["phash"];
$subject = 'Your Login Link';
if(!User::exists($email)){
$subject = "Thank You for Registering!";
$message = "Thank you for registering at our site!\n\n";
// Attempt to login or register the person
$user = User::loginOrRegister($email, $name, $phash);
$message.= "You can login from this URL:\n";
$message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";
$message.= "The link is going expire automatically after 10 minutes.";
$result = send_email($fromEmail, $_POST['email'], $subject, $message);
if(!$result){
sendResponse(403, 'Error Sending Email');
return false;
}
}
else{
sendResponse(150, 'User Already Registered');
return false;
}
}
else if(isset($_POST["email"]) && isset($_POST["phash"])){
rate_limit($_SERVER['REMOTE_ADDR']);
rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);
$message = '';
$name = '';
$email = $_POST["email"];
$phash = $_POST["phash"];
$subject = 'Your Login Link';
if(!User::exists($email)){
sendResponse(155, 'User Not Registered');
return false;
}
else{
// Attempt to login or register the person
$user = User::loginOrRegister($email, $name, $phash);
$message.= "You can login from this URL:\n";
$message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";
$message.= "The link is going expire automatically after 10 minutes.";
$result = send_email($fromEmail, $_POST['email'], $subject, $message);
if(!$result){
sendResponse(403, 'Error Sending Email');
return false;
}
}
}
die(json_encode(array(
'message' => 'Thank you! We\'ve sent a link to your inbox. Check your spam folder as well.'
)));
/*--------------------------------------------------
Output the login form
---------------------------------------------------*/
}
}
$api = new dumb;
$api->dumber();
?>
I had a syntax error. A / after the closing php tag :O. Sorry

Categories