I wish to create an authorization system in my iOS app. I have to ship a affirmation e mail when registering a consumer. I do not know PHP
very properly, however I discovered a few examples for registering and logging customers with mysql
(phpMyAdmin
) database. Now in my code I can register or login consumer. Since I do not know a lot about PHP
, I do not fairly perceive add the e-mail affirmation code to my present PHP
code. I wish to add new PHP
code to my present PHP
recordsdata to despatched affirmation e mail and efficiently end register. My code:
My php code:
Constants:
<?php
outline('DB_USERNAME', 'DB_USERNAME');
outline('DB_PASSWORD', 'DB_PASSWORD');
outline('DB_HOST', 'DB_HOST');
outline('DB_NAME', 'DB_NAME');
outline('USER_CREATED', 0);
outline('USER_ALREADY_EXIST', 1);
outline('USER_NOT_CREATED', 2);
DbConnect:
<?php
class DbConnect
{
personal $conn;
perform __construct()
{
}
/**
* Establishing database connection
* @return database connection handler
*/
perform join()
{
require_once 'Constants.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Examine for database connection error
if (mysqli_connect_errno()) {
echo "Failed to hook up with MySQL: " . mysqli_connect_error();
}
// returing connection useful resource
return $this->conn;
}
}
DbOperation:
<?php
class DbOperation
{
personal $conn;
perform __construct()
{
require_once dirname(__FILE__) . '/Constants.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->join();
}
/*
* This methodology is added
* We're taking username and password
* after which verifying it from the database
* */
public perform userLogin($username, $move)
{
$password = md5($move);
$stmt = $this->conn->put together("SELECT id FROM customers WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
/*
* After the profitable login we are going to name this methodology
* this methodology will return the consumer knowledge in an array
* */
public perform getUserByUsername($username)
{
$stmt = $this->conn->put together("SELECT id, username, e mail, telephone FROM customers WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($id, $uname, $e mail, $telephone);
$stmt->fetch();
$consumer = array();
$consumer['id'] = $id;
$consumer['username'] = $uname;
$consumer['email'] = $e mail;
$consumer['phone'] = $telephone;
return $consumer;
}
public perform createUser($username, $move, $e mail, $title, $telephone)
{
if (!$this->isUserExist($username, $e mail, $telephone)) {
$password = md5($move);
$stmt = $this->conn->put together("INSERT INTO customers (username, password, e mail, title, telephone) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $username, $password, $e mail, $title, $telephone);
if ($stmt->execute()) {
return USER_CREATED;
} else {
return USER_NOT_CREATED;
}
} else {
return USER_ALREADY_EXIST;
}
}
personal perform isUserExist($username, $e mail, $telephone)
{
$stmt = $this->conn->put together("SELECT id FROM customers WHERE username = ? OR e mail = ? OR telephone = ?");
$stmt->bind_param("sss", $username, $e mail, $telephone);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
}
login:
<?php
require_once '../contains/DbOperation.php';
$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['username']) && isset($_POST['password'])) {
$db = new DbOperation();
if ($db->userLogin($_POST['username'], $_POST['password'])) {
$response['error'] = false;
$response['user'] = $db->getUserByUsername($_POST['username']);
} else {
$response['error'] = true;
$response['message'] = 'Invalid username or password';
}
} else {
$response['error'] = true;
$response['message'] = 'Parameters are lacking';
}
} else {
$response['error'] = true;
$response['message'] = "Request not allowed";
}
echo json_encode($response);
register:
<?php
//importing required script
require_once '../contains/DbOperation.php';
$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!verifyRequiredParams(array('username', 'password', 'e mail', 'title', 'telephone'))) {
//getting values
$username = $_POST['username'];
$password = $_POST['password'];
$e mail = $_POST['email'];
$title = $_POST['name'];
$telephone = $_POST['phone'];
//creating db operation object
$db = new DbOperation();
//including consumer to database
$end result = $db->createUser($username, $password, $e mail, $title, $telephone);
//making the response accordingly
if ($end result == USER_CREATED) {
$response['error'] = false;
$response['message'] = 'Person created efficiently';
} elseif ($end result == USER_ALREADY_EXIST) {
$response['error'] = true;
$response['message'] = 'Person exist already';
} elseif ($end result == USER_NOT_CREATED) {
$response['error'] = true;
$response['message'] = 'Some error occurred';
}
} else {
$response['error'] = true;
$response['message'] = 'Required parameters are lacking';
}
} else {
$response['error'] = true;
$response['message'] = 'Invalid request';
}
//perform to validate the required parameter in request
perform verifyRequiredParams($required_fields)
{
//Getting the request parameters
$request_params = $_REQUEST;
//Looping by all of the parameters
foreach ($required_fields as $discipline) {
//if any requred parameter is lacking
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
//returning true;
return true;
}
}
return false;
}
echo json_encode($response);
My swift code in app:
LoginViewController
class LoginViewController: UIViewController {
// Net Service URL
let URL_USER_LOGIN = "http://instance.com/DB/v1/login.php"
// The DefaultValues to Retailer Person Information
let defaultValues = UserDefaults.commonplace
var textFieldUserName = UITextField()
var textFieldPassword = UITextField()
var labelMessage = UILabel()
var loginButton = UIButton()
var stackView = UIStackView()
override func viewDidLoad() {
tremendous.viewDidLoad()
loginCheck()
interface()
}
// MARK: - Actions
// Login Motion
@objc func buttonLogin(sender: UIButton!) {
// Getting the Username and Password
let parameters: Parameters = [ "username":textFieldUserName.text!, "password":textFieldPassword.text!]
// Making a Publish Request
Alamofire.request(URL_USER_LOGIN, methodology: .put up, parameters: parameters).responseJSON { response in
// Printing Response
print(response)
// Getting the JSON Worth from the Server
if let end result = response.end result.worth {
let jsonData = end result as! NSDictionary
// If There may be No Error
if(!(jsonData.worth(forKey: "error") as! Bool)){
// Getting the Person from Response
let consumer = jsonData.worth(forKey: "consumer") as! NSDictionary
// Getting Person Values
let userId = consumer.worth(forKey: "id") as! Int
let userName = consumer.worth(forKey: "username") as! String
let userEmail = consumer.worth(forKey: "e mail") as! String
let userPhone = consumer.worth(forKey: "telephone") as! String
// Saving Person Values to UserDefaults
self.defaultValues.set(userId, forKey: "userid")
self.defaultValues.set(userName, forKey: "username")
self.defaultValues.set(userEmail, forKey: "useremail")
self.defaultValues.set(userPhone, forKey: "userphone")
// Switching the Display screen
let profileViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProfileViewcontroller") as! ProfileViewController
self.navigationController?.pushViewController(profileViewController, animated: true)
self.dismiss(animated: false, completion: nil)
}else{
// Error Message in Case of Invalid Credential
self.labelMessage.textual content = "Invalid username or password"
}
}
}
}
// MARK: - Login Examine
func loginCheck() {
// If Person is Already Logged in Switching to Profile Display screen
if defaultValues.string(forKey: "username") != nil {
let profileViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProfileViewcontroller") as! ProfileViewController
self.navigationController?.pushViewController(profileViewController, animated: true)
}
}
}
RegistrationViewController
class RegistrationViewController: UIViewController {
// Net Service URL
let URL_USER_REGISTER = "http://instance.com/DB/v1/register.php"
var textFieldUsername = UITextField()
var textFieldPassword = UITextField()
var textFieldEmail = UITextField()
var textFieldName = UITextField()
var textFieldPhone = UITextField()
var labelMessage = UILabel()
var registerButton = UIButton()
var stackView = UIStackView()
//Button Motion
@objc func buttonRegister(sender: UIButton!) {
//creating parameters for the put up request
let parameters: Parameters = [
"username":textFieldUsername.text!,
"password":textFieldPassword.text!,
"name":textFieldName.text!,
"email":textFieldEmail.text!,
"phone":textFieldPhone.text!]
// Sending HTTP Publish request
Alamofire.request(URL_USER_REGISTER, methodology: .put up, parameters: parameters).responseJSON {
response in
// Printing Response
print(response)
// Getting the JSON Worth from the Server
if let end result = response.end result.worth {
// Changing it as NSDictionary
let jsonData = end result as! NSDictionary
// Displaying the Message in Label
self.labelMessage.textual content = jsonData.worth(forKey: "message") as! String?
}
}
}
}