Следующее руководство this, чтобы узнать, как создать API для Android. Проверял мой файл DB_Functions.php
, и все подключается и работает правильно (на 90% уверен). Чтобы убедиться, что почта работает правильно, я использую chrome add-on, называемый Postman
. This Другой вопрос, который я нашел в Интернете, имел аналогичную проблему с моей. Это то, что я ввел/получил.
Вот кодВставить в базу данных MySQL с помощью PHP API
<?php
/*
Function tests
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$insert = $db->storeUser("InsertTest", "[email protected]", "apple");
print_r($insert);
$user = $db->getUserByEmailAndPassword("[email protected]", "apple");
print_r($user);
$exist = $db->isUserExisted("[email protected]");
echo $exist; */
/**
* File to handle all API requests
* Accepts GET and POST
*
* Each request will be identified by TAG
* Response will be JSON data
/**
* check for POST request
*/
if (isset($_POST['tag']) && $_POST['tag'] != '') {
$tag = $_POST['tag'];
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$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 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 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 is already existed
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = TRUE;
$response["error_msg"] = "User already existed";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$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 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"] = "Unknown '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);
}
?>
И код DB_Functions.php
<?php
class DB_Functions{
private $db;
public $connection;
function __construct(){
require_once ('DB_Connect.php');
$this->db = new DB_Connect();
$this->connection = $this->db->connect();
}
function __destruct(){
}
public function storeUser($name, $email, $password){
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"];
$salt = $hash["salt"];
$sql = "INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at)
VALUES ('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())";
$result = $this->connection->query($sql);
if($result){
$uid = mysqli_insert_id($this->connection);
$sql = "SELECT * FROM users WHERE uid = '" . $uid . "';";
$result = $this->connection->query($sql);
return mysqli_fetch_array($result);
}else{
return false;
}
}
public function getUserByEmailAndPassword($email, $password){
$sql = "SELECT * FROM users WHERE email = '" . $email . "';";
$result = $this->connection->query($sql);
$no_of_rows = mysqli_num_rows($result);
if($no_of_rows > 0){
$result = mysqli_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
if($encrypted_password == $hash){
return $result;
}
}else{
return false;
}
}
public function isUserExisted($email){
$sql = "SELECT * FROM users WHERE email = '" . $email . "';";
$result = $this->connection->query($sql);
$no_of_rows = mysqli_num_rows($result);
if($no_of_rows > 0){
return true;
}else{
return false;
}
}
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;
}
public function checkhashSSHA($salt, $password){
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
Кто-нибудь знает, почему сообщение не работает?
** ПРЕДУПРЕЖДЕНИЕ **: при использовании 'mysqli' вы должны использовать параметризованные запросы и [' bind_param'] (http://php.net/manual/en/mysqli-stmt.bind-param.php) для добавьте данные пользователя в ваш запрос. ** НЕ используйте ** интерполирование строк или конкатенацию, чтобы выполнить это, потому что вы создадите серьезные [SQL-инъекции ошибок] (http://bobby-tables.com/). ** НИКОГДА ** не вводите данные '$ _POST' непосредственно в запрос. – tadman
Также ваш скриншот совершенно неразборчив. Что мы должны отнять от этого? – tadman
Вы должны использовать встроенные функции PHP (http://jayblanchard.net/proper_password_hashing_with_PHP.html) для защиты паролей. –