I am following the tutorial on Androidhive about registering with sqlite and php:
I have implemented everything and it seems the app is working fine. The problem seems to be on the serverside as it gives me an Unexpected response code 500.
my code for logging in:
package com.example.sqltest2;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.sqltest2.AppConfig;
import com.example.sqltest2.AppController;
import com.example.sqltest2.SessionManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends Activity {
// LogCat tag
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
System.out.println("Login button clicked");
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
System.out.println("trying to login");
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
System.out.println("JSONException caught: ");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
System.out.println("getParams login");
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
my code on the server:
/include/Config.php
<?php
/**
* Created by PhpStorm.
* User: 01222_000
* Date: 08/05/2015
* Time: 18:16
*/
/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "asus");
define("DB_DATABASE", "android_api");
/include/DB_Connect.php
<?php
/**
* Created by PhpStorm.
* User: 01222_000
* Date: 08/05/2015
* Time: 18:19
*/
class DB_Connect {
public $dbh;
// constructor
function __construct() {
$this->connect();
}
// destructor
function __destruct() {
$this->close();
}
// connecting to database
public function connect() {
require_once 'include/Config.php';
// connect to mysql or die
try {
$dbh = new PDO('mysql:host=localhost;dbname=android_api', DB_USER, DB_PASSWORD);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
return $dbh;
}
//close database connection
public function close() {
$dbh = null;
}
}
/include/DB_Functions.php
<?php
/**
* Created by PhpStorm.
* User: 01222_000
* Date: 08/05/2015
* Time: 19:06
*/
class DB_Functions {
private $db;
private $dbh;
//constructor
function __construct() {
require_once 'DB_Connect.php';
$this->db = new DB_Connect();
$this->db->connect();
$this->dbh = $this->db->connect();
}
//destructor
function __destruct() {
$this->db->close();
}
// store new user
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$query = "INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name, '$email', '$encrypted_password', '$salt', NOW())";
$result = $this->dbh->query($query);
//check for succesful store
if ($result) {
// get user details
$uid = $this->dbh->lastInsertId(); // last inserted id
$stmt = $this->dbh->prepare("SELECT * FROM users WHERE uid = $uid");
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
else {
return false;
}
}
// get user by email and password
public function getUserByEmailAndPassword($email, $password) {
// execute query and store all results
$stmt = $this->dbh->prepare("SELECT * FROM users WHERE email = '$email'");
$stmt->execute();
$result = $stmt->fetchAll();
// check the results
$no_of_rows = count($result);
if ($no_of_rows > 0) {
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check if passwords match
if($encrypted_password == $hash) {
// user authentication succeeded, return results
return $result;
}
}
else {
// user not found
return false;
}
}
// check if user exists using only email
public function isUserExisted($email) {
$stmt = $this->dbh->prepare("SELECT email FROM users WHERE email = '$email'");
$stmt->execute();
$result = $stmt->fetchAll();
// check for results
$no_of_rows = count($result);
if ($no_of_rows > 0) {
// user exists
return true;
}
else {
// user does not exist
return false;
}
}
/**
* Encrypting password
* @param password
* @return array with salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* @param $salt
* @param $password
*
* Decrypting password
* @return hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
/index.php
<?php
/**
* Created by PhpStorm.
* User: 01222_000
* Date: 08/05/2015
* Time: 20:40
*
* File to handle all API requests
* Accepts GET and POST
*
* Each request will be identified by TAG
* Response is JSON data
*/
// check for POST request
if(isset($_POST['tag']) && $_POST['tag'] != '') {
$tag = $_POST['tag'];
// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response array
$response = array("tag" => $tag, "error" => FALSE);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user was 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"];
echo json_encode($response);
} else {
// user was not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// request type is: register new user
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// check if user already exists
if ($db->isUserExisted($email)) {
// user already exists
$response["error"] = TRUE;
$response["error_msg"] = "User already exists";
echo json_encode($response);
} else {
// user does not exist already
// so store the new user into the database
$user = $db->storeUser($name, $email, $password);
// check if user was stored correctly
if ($user) {
// user has been stored succesfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter 'tag' is missing!";
echo json_encode($response);
}
tcpdump output from the server:
14:17:54.181682 IP 192.168.1.100.59628 > debian.local.http: Flags [S], seq 3478971437, win 14600, options [mss 1460,sackOK,TS val 3399978 ecr 0,nop,wscale 6], length 0
E..<..@.@......d...u...P.\.-......9............
.3.*........
14:17:54.181927 IP debian.local.http > 192.168.1.100.59628: Flags [S.], seq 3960639023, ack 3478971438, win 14480, options [mss 1460,sackOK,TS val 820427 ecr 3399978,nop,wscale 4], length 0
E..<..@.@......u...d.P...../.\....8..X.........
.....3.*....
14:17:54.184937 IP 192.168.1.100.59628 > debian.local.http: Flags [.], ack 1, win 229, options [nop,nop,TS val 3399980 ecr 820427], length 0
E..4..@.@......d...u...P.\.....0....tk.....
.3.,....
14:17:54.322646 IP 192.168.1.100.59628 > debian.local.http: Flags [P.], seq 1:314, ack 1, win 229, options [nop,nop,TS val 3399993 ecr 820427], length 313
E..m. @.@..X...d...u...P.\.....0..../G.....
.3.9....POST /android_login_api/index.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)
Host: 192.168.1.117
Connection: Keep-Alive
Accept-Encoding: gzip
Content-Length: 29
password=d&email=d&tag=login&
14:17:54.322763 IP debian.local.http > 192.168.1.100.59628: Flags [.], ack 314, win 972, options [nop,nop,TS val 820463 ecr 3399993], length 0
E..4
.@.@......u...d.P.....0.\.g.....P.....
.....3.9
14:17:54.328145 IP debian.local.http > 192.168.1.100.59628: Flags [P.], seq 1:274, ack 314, win 972, options [nop,nop,TS val 820464 ecr 3399993], length 273
E..E
.@.@......u...d.P.....0.\.g.....a.....
.....3.9HTTP/1.0 500 Internal Server Error
Date: Sun, 10 May 2015 12:17:54 GMT
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.39-0+deb7u2
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 20
Connection: close
Content-Type: text/html
....................
14:17:54.330375 IP debian.local.http > 192.168.1.100.59628: Flags [F.], seq 274, ack 314, win 972, options [nop,nop,TS val 820465 ecr 3399993], length 0
E..4
.@.@......u...d.P.....A.\.g.....P.....
.....3.9
14:17:54.330959 IP 192.168.1.100.59628 > debian.local.http: Flags [.], ack 274, win 229, options [nop,nop,TS val 3399994 ecr 820464], length 0
E..4.
@.@......d...u...P.\.g...A....q......
.3.:....
14:17:54.336656 IP 192.168.1.100.59628 > debian.local.http: Flags [F.], seq 314, ack 275, win 229, options [nop,nop,TS val 3399995 ecr 820465], length 0
E..4..@.@......d...u...P.\.g...B....q......
.3.;....
14:17:54.336732 IP debian.local.http > 192.168.1.100.59628: Flags [.], ack 315, win 972, options [nop,nop,TS val 820466 ecr 3399995], length 0
E..4
.@.@......u...d.P.....B.\.h.....P.....
.....3.;
apache errorlog:
[Sun May 10 14:15:23 2015] [error] [client 192.168.1.100] PHP Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0
[Sun May 10 14:15:23 2015] [error] [client 192.168.1.100] PHP Fatal error: Unknown: Failed opening required '/var/www/android_login_api/index.php' (include_path='.:/usr/share/php:/usr/share/pear') in Unknown on line 0
[Sun May 10 14:15:24 2015] [error] [client 192.168.1.100] PHP Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0
[Sun May 10 14:15:24 2015] [error] [client 192.168.1.100] PHP Fatal error: Unknown: Failed opening required '/var/www/android_login_api/index.php' (include_path='.:/usr/share/php:/usr/share/pear') in Unknown on line 0
[Sun May 10 14:15:25 2015] [error] [client 192.168.1.100] PHP Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0
[Sun May 10 14:15:25 2015] [error] [client 192.168.1.100] PHP Fatal error: Unknown: Failed opening required '/var/www/android_login_api/index.php' (include_path='.:/usr/share/php:/usr/share/pear') in Unknown on line 0
[Sun May 10 14:17:29 2015] [error] [client 192.168.1.100] PHP Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0
[Sun May 10 14:17:29 2015] [error] [client 192.168.1.100] PHP Fatal error: Unknown: Failed opening required '/var/www/android_login_api/index.php' (include_path='.:/usr/share/php:/usr/share/pear') in Unknown on line 0
[Sun May 10 14:17:54 2015] [error] [client 192.168.1.100] PHP Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0
[Sun May 10 14:17:54 2015] [error] [client 192.168.1.100] PHP Fatal error: Unknown: Failed opening required '/var/www/android_login_api/index.php' (include_path='.:/usr/share/php:/usr/share/pear') in Unknown on line 0
apache accesslog
192.168.1.100 - - [10/May/2015:13:46:18 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
192.168.1.100 - - [10/May/2015:14:00:18 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
192.168.1.100 - - [10/May/2015:14:00:26 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
192.168.1.100 - - [10/May/2015:14:15:05 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
192.168.1.100 - - [10/May/2015:14:15:09 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
192.168.1.100 - - [10/May/2015:14:15:23 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
192.168.1.100 - - [10/May/2015:14:15:24 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
192.168.1.100 - - [10/May/2015:14:15:25 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
192.168.1.100 - - [10/May/2015:14:17:29 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
192.168.1.100 - - [10/May/2015:14:17:54 +0200] "POST /android_login_api/index.php HTTP/1.1" 500 273 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; HUAWEI G6-L11 Build/HuaweiG6-L11)"
So the problem seems to be inside index.php but I cannot figure out what it is exactly. I also have no idea how to debug this kind of problem as I am pretty new to all this.
All I could think of was permission rights of index.php because of the error in the log so I gave it 'Chmod +x' to give it execution rights for everyone but that also does not work.
My question is: What could the problem be here?
Aucun commentaire:
Enregistrer un commentaire