Throw connection error at front end php - php

so I am a php beginner and i was making a login app with server and client side validation .I want to throw an error to the login page when the password is wrong after matching it with db or if email is not unique ..well something like that.
Thank you

To display authentication error after checking from DB you need to use ajax
var username = "....";
var password = "....";
$.ajax({
url: "/login",
method: "POST",
data:{username,password}
}).done(function(data) {
if(data.success){
$("#msg").html("Success");
}else{
$("#msg").html(data.err_msg);
}
});
In php files
<?php
function checkAuthentication(){
$errormsg = "";
$result = true;
try {
//your data and query to check 'username' and 'password'
if(!$password_match){
$result = false;
$errormsg = 'Invalid credential';
}
} catch (Exception $exception) {
$result = false;
$errormsg = 'Database error! ' . $exception->getMessage();
}
//return json data
return json_encode(["success"=>$result,"err_msg"=>$errormsg]);
}
?>
There are much more things to do but you can think this way to start

Related

How would I authentication users logging in to my iOS app with alamofire in swift 5?

I thought I finished my login system but it turned out I could write random letters and to be able to proceed to my tab bar controller. The information didn't authenticate. This is my first app and I'm not sure where to start. Any help on this problem?
Here is my login.php code:
<?php
//Step 1 Check variables passing to this file via POST
$username = htmlentities($_REQUEST["username"]);
$password = htmlentities($_REQUEST["password"]);
if (empty($username) || empty($password)) {
$returnArray["status"] = "400";
$returnArray["message"] = "Missing required information";
echo json_encode($returnArray);
return;
}
//Step 2. Build connection
//Secure way to build conn
$file = parse_ini_file("../../../iHertzmusic.ini");
// store in php var inf from ini var
$host = trim($file["dbhost"]);
$user = trim($file["dbuser"]);
$pass = trim($file["dbpass"]);
$name = trim($file["dbname"]);
// include access.php to call func from access.php file
require ("secure/access.php");
$access = new access($host, $user, $pass, $name);
$access->connect();
//Step 3. Get user information
//Assign result of execution of getUser to $user var
$user = $access->getUser($username);
//if we did not get any user information
if (empty($user)) {
$returnArray["statusCode"] = "403";
$returnArray["message"] = "User is not found";
echo json_encode($returnArray);
return;
}
//Step 4. Check validity of entered password
//get password and salt from db
$secured_password = $user["password"];
$salt = $user["salt"];
// check do passwords match: from db & entered one
if ($secured_password == sha1($password . $salt)) {
$returnArray["statusCode"] = "200";
$returnArray["message"] = "Logged in successfully";
$returnArray["id"] = $user["id"];
$returnArray["username"] = $user["username"];
$returnArray["email"] = $user["email"];
$returnArray["fullname"] = $user["fullname"];
} else {
$returnArray["statusCode"] = "403"; //changed
$returnArray["message"] = "passwords do not match";
}
//STEP 5. Close connection
$access->disconnect();
//STEP 6. Throw back all infomation to users
echo json_encode($returnArray);
?>
Here is my .swift code
#IBAction func loginTapped(_ sender: Any) {
// If no text entered
if usernameTextfield.text!.isEmpty || passwordTextField.text!.isEmpty {
//send message if fields are not filled
print("User name \(String(describing: usernameTextfield)) or password \(String(describing: passwordTextField)) is empty")
self.errorLabel.alpha = 1
return
} else {
//Shortcuts
let username = usernameTextfield.text
let password = passwordTextField.text
//send request to sql db
let url = "http://10.0.0.157/iHertzmusic/login.php"
let parameters: Parameters=[
"username":usernameTextfield.text!,
"password":passwordTextField.text!
]
AF.request(url, method: .post, parameters: parameters as Parameters, encoding:
URLEncoding.default).validate().response { (response) in
switch response.result {
case .success:
//sign in
let tabVC =
self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.TabBarController) as? UITabBarController
self.view.window?.rootViewController = tabVC
self.view.window?.makeKeyAndVisible()
case .failure(let error):
// Couldn't sign in
self.errorLabel.text = error.localizedDescription
self.errorLabel.alpha = 1
}
}
Based on the answer to What is the use of the validate() method in Alamofire.request?:
It would appear that the issue is due to the fact that you are returning the statusCode in the field status and are using a String and not an Int.
Try changing
$returnArray["status"] = "403";
to:
$returnArray["statusCode"] = 403;
and
$returnArray["status"] = "200";
to:
$returnArray["statusCode"] = 200;
If your php code returns success, you should save some data into app like
UserDefaults.standard.set(true, forKey: "isLoggedIn")
and then in your appdelegate you should check this value
let isLoggedIn = UserDefaults.standard.bool(forKey: "isLoggedIn")
if isLoggedIn {
// push main view cont
} else {
//not logged in show login view
}
you may need additional data like user info and want to save object see
Save custom objects into NSUserDefaults
this is just for swift code didn't check your php api is correcty written

JQUERY AJAX GET and POST accessing different files?

I am doing email verification on my website. When user submits the form, it starts ajax post request, which posts the email to PHP which compares it with a datebase.
Than still in the form verification process, I have ajax GET request, which should return from the same PHP file whether the email has already been used.
But. Everything works fine when I proceed to the PHP, but GET request is always blank. URL of POST request is EmailDuplication.php but URL of GET is EmailDuplication?_=somerandomnumbers. Might that be the problem?
I am not experienced in this, will be glad for any help.
Here are the codes
JavaScript
function EmailSendForDupe()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'post',
async: false,
cache: false,
timeout: 30000,
data: {email: email.toString},
success: function (){
window.alert("email sent");
}
});
}
function EmailDuplication()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
async: false,
cache: false,
timeout: 30000,
success: function (callback){
console.log(callback.length);
console.log(callback);
if (callback.length !== 0){
window.alert("Email is already in use");
return false;
}
else {
window.alert("Email valid");
return true;
}
}
});
}
PHP
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}
else {
echo "User Email is already in use.";
}
}
?>
First, I would advise cleaning up your PHP and making sure it is not vulnerable to SQL Injection.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
$returnData = new array();
$conn = mysqli_connect($servername, $username,$password,$dbname);
if (mysqli_connect_errno()) {
$returnData['SQL Error'] = "Connect failed: %s\n", mysqli_connect_error();
header('Content-Type: application/json');
echo json_encode($returnData);
exit();
}
if(isset($_POST['email'])){
// POST
$email = mysqli_real_escape_string($conn, $_POST['email']);
$resultData["AHOJ"] = true;
$Emailquery = "SELECT * FROM Members WHERE email='$email' LIMIT 1;";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
$resultData['inUse'] = false;
$resultData['email'] = $_POST['email'];
} else {
$resultData['inUse'] = true;
}
} else {
// GET
$resultData["AHOJ"] = false;
$resultData['inUse'] = true;
}
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($returnData);
die();
?>
This will return JSON details back to your jQuery script and can be more helpful than plain text.
I also use mysqli_real_escape_string() to help escape any potential injection attempts. I would advise switching to Prepared statements: http://php.net/manual/en/mysqli-stmt.prepare.php
In your JavaScript, you will want to make a few changes too.
function EmailSendForDupe(email){
$.ajax({
url: '/files/EmailDuplication.php',
type: 'post',
cache: false,
timeout: 30000,
data: {
email: email.toString()
},
dataType: "json",
success: function (json){
console.log(json);
if(json.inUse == false){
alert("Email Sent to " + json.email);
} else {
alert("There may have been an error: " + json.error);
}
}
});
}
function EmailDuplication(email){
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
data: {
email: email.toString()
},
dataType: "json",
cache: false,
timeout: 30000,
success: function (json){
console.log(json);
if (json.inUse){
window.alert("Email is already in use");
} else {
window.alert("Email valid");
}
}
});
}
Hope this helps.
Generally you want to use async: true.
Also, you do not want to allow the form submit to actually Happen, as that blows away your whole page (reloads the entire thing, if not navigates to somewhere else entirely). So in fact the blank get you could be seeing could be the form submit blowing away your page.
If you are sending ajax requests, the trigger for those simply needs to be a button with a click handler, not an actual submit (unless in that submit input you do something like "onclick='doMyAjax();return false;'" so that the submit action does not actually occur).
If you are actually uploading a file, which for the purpose you appear to be showing here dear goodness please don't let the client drive that functionality via files on their system, the upload post needs a target to post To, so it does not hit your page. For that, the classic embedding of an iframe is still the way to go. Ugh.
posting to an iframe
I have no idea why Two requests need to be sent to do the job. It should probably be just one POST (assuming the ultimate outcome here is you want to send an email if it is a valid email), and the server checks the email and then does the send if it is valid.
And do not use GET versus POST to distinguish what the server should do (such as verifying an email versus sending one) - the Request itself or the Url, for example include "action=verifyEmail" in your form data being passed up, to tell the server what to do rather than it assuming just because it's a POST.
Hopefully some of this is helpful.
you are missing to handle GET Request Data.if some try to using get URL then your code don't have any condition to handle it. check modified code.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}else {
echo "User Email is already in use.";
}
}else{
echo " Get Method Data";
}
?>
Please try it and give your feedback.

Page Redirection in Micro Slim PHP Framework?

i am facing issue regarding Page Redirection in PHP Micro Slim Framework #version 2.3.5.
i have already Try few Ways to Redirect but all the way i try are not working.
Actually i have a login Page and on submit i am calling the The Login Check Function which i have write and it is working properly. But finally after Successful MATCH of Username and Password, i want to redirect on another page.
the ways i have already tried are below:
return $response->withRedirect('/dashboard.php');
return $response->withStatus(302)->withHeader('Location', 'http://localhost/kafcashapp/dashboard.php');
$app->redirect('http://localhost/kafcashapp/dashboard.php', 301);
header("Location: http://localhost/kafcashapp/dashboard.php");
Below are the Code to Check Login
$app->post('/login', function() use ($app) {
// check for required params
verifyRequiredParams(array('email', 'password'));
// reading post params
$email = $app->request()->post('email');
$password = $app->request()->post('password');
$response = array();
$db = new DbHandler();
// check for correct email and password
if ($db->checkLogin($email, $password)) {
// get the user by email
$user = $db->getUserByEmail($email);
if ($user != NULL) {
$response["error"] = false;
$response['name'] = $user['name'];
$response['email'] = $user['email'];
$response['apiKey'] = $user['api_key'];
$response['createdAt'] = $user['created_at'];
} else {
// unknown error occurred
$response['error'] = true;
$response['message'] = "An error occurred. Please try again";
}
} else {
// user credentials are wrong
$response['error'] = true;
$response['message'] = 'Login failed. Incorrect credentials';
}
//echoRespnse(200, $response);
});
any Suggestion will be appreciated.
Looking at the documentation you can do 302 Temporary Redirect with the following.
$app->redirect("/bar");
If you need 301 Moved Permanently instead you need to specify the status code manually.
$app->redirect("/bar", 301);

Failure to create login script (Post 500 internal server error)

I am having an issue with a brand new site I am trying to create, Its pretty basic right now, and I am just playing around with seeing how I like to do things.
So I have a place where I can log in currently, just two forms and a button. And I would like to use Ajax to call a php script that handles the login and then spits out a response depending on how it goes.
Here is what I have.
HTML:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<form id="key-form" name="keyform" action="scriptLogin.php" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" class="button" value="Login">
</form>
Ajax Call:
$(document).ready(function(){
$("#key-form").submit(function(e) {
e.preventDefault(); // stop normal form submission
$.ajax({
url: "scriptLogin.php",
type: "POST",
data: $(this).serialize(), // you also need to send the form data
dataType: "json",
success: function(data){ // this happens after we get results
$("#response").show();
$("#response").html("");
// If there is no error the response will be {"success":true}
// If there is any error means the response will be {"error":["1":"error",..]}
if(data.success){
$("#response").prepend("<h3>Successfully Logged In</h3>");
}else{
$.each(data.error, function(index, val){
$("#response").prepend("<h3>" +val+ '</h3>');
});
}
}
});
});
});
scriptLogin.php
<?php
session_start();
// Database configuration
// Not the real credentials obviously
define('DB_HOST', 'dbhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'dbname');
// Initializing error array
$response['error'] = array();
try {
$db = new PDO('mysql:host=' . DB_HOST .';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (Exception $e) {
$response['error'][] = "Error in DB Connection";
}
// Store post and session values to variable.
$username = $_POST['username'];
$password = $_POST['password'];
$key = $_POST['key'];
// Validating Password
if($password === '' || $password === FALSE ){
$response['error'][] = "Your Password cannot be blank";
}
if($username === '' || $username === FALSE ){
$response['error'][] = "Your Username is too short!";
}
// If validation password update the password for the user.
if(empty($response['error'])){
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
//Carry out the query
$stmt->execute();
$hash = $stmt['hash'];
$affectedRows = $stmt->rowCount(); // Getting affected rows count
if($affectedRows != 1){
$response['error'][] = "No User is related to the Username";
}
if(password_verify($password, $hash))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $stmt['ID'];
}
else
{
$response['error'][] = "Your password is invalid.";
}
}
// printing response.
if(!empty($response['error'])){
echo json_encode($response);
}else{
echo json_encode(array("success"=>true));
}
?>
So whenever I try and log in. I get this error:
POST http://website.net/scriptLogin.php 500 (Internal Server Error)
m.ajaxTransport.send # jquery.min.js:4
m.extend.ajax # jquery.min.js:4
(anonymous function) # (index):62
m.event.dispatch # jquery.min.js:3
m.event.add.r.handle # jquery.min.js:3
I need a shove in the correct direction. I checked the sites error page on cpanel. I have nothing for this. Im baffled.
EDIT #1:
Here is the error from loginScript.php
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in /home/mcomputers/public_html/key/scriptLogin.php:40 Stack trace: #0 /home/mcomputers/public_html/key/scriptLogin.php(40): PDOStatement->bindParam(':password', NULL) #1 {main} thrown in /home/mcomputers/public_html/key/scriptLogin.php on line 40

PHP and jQuery AJAX $_SESSION Bug

I spent many days to fix this problem and i can't find a solution.
After i login using my ajax form + php backend, the page where user is redirected show the "Missing session" message and if i try dumping $_SESSION it looks like empty. Then, if i go back and i do the same login it will work correctly. This happen in different browser (usually when they have cookie and cache clear) and in different hosting providers.
This is my ajax code:
$(document).ready(function(){
$('#loginbtn').click(function(){
if($('#username').val() == "" || $('#password').val() == ""){
return false;
}
else
{
$.ajax
({
type: 'POST',
url: 'ajax_login.php',
cache: false,
dataType: 'json',
data:
{
username: $('#username').val(),
password: $('#password').val()
},
success:function(data)
{
if(data.error === true){
alert("Failed to login: "+data.message)
}
else
{
setTimeout(function()
{
window.location = 'http://www.mywebsite.com/dashboard.php';
},2000);
}
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("An error occured!");
}
});
return false;
}
});
});
This is the PHP Login Backend:
<?php
include "config.php"; // start session and connect to mysql db, also contain functions sanitize(), getip()
$username = sanitize(htmlspecialchars($_POST['username'],ENT_QUOTES));
$pass = sanitize($_POST['password']);
// FUNCTION TO LOGIN
$sql = mysql_query("SELECT * FROM members WHERE username = '$username' AND password = '$pass'");
$array = mysql_fetch_array($sql);
if(mysql_num_rows($sql) === 0){
$message['error'] = true;
$message['message'] = "Wrong username or password.";
echo json_encode($message);
exit;
}
$_SESSION['username'] = ucwords(strtolower($username));
$_SESSION['points'] = $array['points'];
$_SESSION['ip'] = getip();
$_SESSION['welcome'] = true;
$message['error'] = false;
$message['message'] = "Completato.";
echo json_encode($message);
exit;
And finally this is dashboard.php check session code:
<?php
include "config.php";
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
if($_SESSION['username'] == "") {
header("Location: index.php?nosession");
exit;
}
Edit: This is what's inside config.php
<?
session_start();
date_default_timezone_set("Europe/Rome");
$hostname = ""; //hostname
$data_username = "dbxxxxxxxx"; //database username
$data_password = "xxxxx"; //database password
$data_basename = "dbxxxxxxx"; //database name
$conn = mysql_connect("".$hostname."","".$data_username."","".$data_password."");
mysql_select_db("".$data_basename."") or die(mysql_error());
function sanitize($text) { // funzione che pulisce le stringe per prevenire exploit;
if(get_magic_quotes_gpc() == 0) {
$text = addslashes($text);
}
$text = htmlentities($text);
$text = strip_tags($text);
$escape = mysql_real_escape_string($text);
$arraydangerous = array('SELECT *', 'LOAD_FILE', 'DELETE', 'TRUNCATE', '\' OR', '<javascript>', 'src=', '<?', '?>', 'document.cookie', 'http://', 'www.');
$text = str_replace($arraydangerous, "", $text);
return $text;
}
function getip()
{
return filtra($_SERVER['HTTP_CF_CONNECTING_IP']); // I use CloudFlare ,so i must use this way :)
}
How can i fix this? Thanks
In config.php add this lines after session_start();.
session_start();
// reset the session, if not logged-in
if (empty($_SESSION['username'])) {
$_SESSION['username'] = null;
$_SESSION['points'] = null;
$_SESSION['ip'] = null;
$_SESSION['welcome'] = null;
}
Also I guess it's better you changing dashboard.php to something like this:
<?php
include "config.php";
if($_SESSION['username'] == "") {
header("Location: index.php?nosession");
exit;
}
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
?>
I think your problem is the old sessions that you have on your server, while testing your code. For example you are trying to log in, you add the values to the session but for any reason you receiving some errors, and you see that you're not logged in. You forgot that you already add some data to the session, you refresh the dashboard.php and you see that hey, it seems that you're already logged in. Then you might think that your code is crazy, working randomly or any other irrelevant reason. (a few years ago, I had a code that was working when it was raining on the day, and didn't work when it wasn't rainy. Fortunately, I solved that problem in 2 days, before getting crazy!)
You might also clean all the sessions stored on your server, to be sure you have a clean test, while you're changing the code.
I hope these gonna helps somehow.
I'm not sure if this is the case or what (since I don't know what's inside config.php), but it seems to me that you forgot to start the session before you use it in your "PHP Login Backend" file!

Categories