It seems that I am having trouble running an SQL query on the server via PHP on Input change. Could someone please take a look on my code and assist me?
The service that is responsible for handling the http request to the server:
import { Injectable } from '#angular/core';
import { HttpClient } from "#angular/common/http";
#Injectable({
providedIn: 'root'
})
export class CrudService {
public url = 'http://localhost/web_api/';
constructor(private http: HttpClient) { }
registerNormal(data)
{
return this.http.post(this.url + 'registerNormal.php', data);
}
accountExists(data)
{
return this.http.get(this.url + 'existingAccounts.php', data);
}
}
The function responsible for passing the data
CheckAccountAvailability(values)
{
const registerNormalFormData = new FormData();
registerNormalFormData.append('username', values.username);
if (this.registerNormal.get('username').valid)
this.crudService.accountExists(registerNormalFormData).subscribe(result => {console.log(result)});
}
The PHP file works fine since I have tested it with postman and also the registerNormal() function works perfectly fine.
I don't seem to pinpoint the issue exactly.
Many thanks!
EDIT:
Below is the html code for the component that calls the function. The function gets called but the result returned by angular is NULL however the PHP API returns the result fine with postman
<input matInput placeholder="User Name" formControlName="username" required (input)="CheckAccountAvailability(registerNormal.value)">
EDIT 2:
Below is the php code for existingAccounts.php
<?php
if ($_GET)
{
// include database connection
include 'config/database.php';
try
{
// check if account exists in database
$q_normalAccountExists = "SELECT * FROM normal_accounts WHERE username=:username";
// $q_bandAccountExists = "SELECT * FROM band_accounts WHERE username=:username";
// prepare queries to check if accounts exist in database
$checkNormalAccount = $con->prepare($q_normalAccountExists);
// $checkBandAccount = $con->prepare($q_bandAccountExists);
// GET username
$username = $_GET['username'];
// bind parameters to check if username exists in database
$checkNormalAccount->bindParam(':username', $username);
// $checkBandAccount->bindParam(':username', $username);
// execute username exists in database query
$checkNormalAccount->execute();
// $checkBandAccount->execute();
if ($checkNormalAccount->rowCount() == 0/* && $checkBandAccount->rowCount() == 0*/)
{
echo json_encode(array('result'=>false));
}
else
{
echo json_encode(array('result'=>true));
}
}
// show error
catch(PDOException $exception)
{
die('ERROR: ' . $exception->getMessage());
}
}
?>
EDIT 3:
It seems that changing the GET request to a POST request sorted the issue. However, could anyone tell me why GET requests won't work?
Related
For about a month, I have been trying to figure out why my code will not return anything after posting a wwwForm (I have also tried the newer equivalent of this function but I had no luck with that either.) The nameField and passwordField are taken from text boxes within the game and the code used in my login script is copied and pasted from a Register script but I have changed the file location to the login.php file. The register script works fine and I can add new users to my database but the login script only outputs "Form Sent." and not the "present" that should return when the form is returned and it never gets any further than that point meaning that it lets the user through with no consequence if they use an invalid name because the script never returns an answer. What should I do to fix this?
Thanks,
Unity Code:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class Login : MonoBehaviour
{
public InputField nameField;
public InputField passwordField;
public Button acceptSubmissionButton;
public void CallLogInCoroutine()
{
StartCoroutine(LogIn());
}
IEnumerator LogIn()
{
WWWForm form = new WWWForm();
form.AddField("username", nameField.text);
form.AddField("password", passwordField.text);
WWW www = new WWW("http://localhost/sqlconnect/login.php", form);
Debug.Log("Form Sent.");
yield return www;
Debug.Log("Present");
if (www.text[0] == '0')
{
Debug.Log("Present2");
DatabaseManager.username = nameField.text;
DatabaseManager.score = int.Parse(www.text.Split('\t')[1]);
Debug.Log("Log In Success.");
}
else
{
Debug.Log("User Login Failed. Error #" + www.text);
}
}
public void Validation()
{
acceptSubmissionButton.interactable = nameField.text.Length >= 7 && passwordField.text.Length >= 8;
}
}
login.php:
<?php
echo "Test String2";
$con = mysqli_connect('localhost', 'root', 'root', 'computer science coursework');
// check for successful connection.
if (mysqli_connect_errno())
{
echo "1: Connection failed"; // Error code #1 - connection failed.
exit();
}
$username = mysqli_escape_string($con, $_POST["username"]);
$usernameClean = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$password = $_POST["password"];
if($username != $usernameClean)
{
echo "7: Illegal Username, Potential SQL Injection Query. Access Denied.";
exit();
}
// check for if the name already exists.
$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE username='" . $usernameClean . "';";
$namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query failed"); // Error code # 2 - name check query failed.
if (mysqli_num_rows($namecheck) != 1)
{
echo "5: No User With Your Log In Details Were Found Or More Than One User With Your Log In Details Were Found"; // Error code #5 - other than 1 user found with login details
exit();
}
// get login info from query
$existinginfo = mysqli_fetch_assoc($namecheck);
$salt = $existinginfo["salt"];
$hash = $existinginfo["hash"];
$loginhash = crypt($password, $salt);
if ($hash != $loginhash)
{
echo "6: Incorrect Password"; // error code #6 - password does not hash to match table
exit;
}
echo "Test String2";
echo"0\t" . $existinginfo["score"];
?>
This problem was solved by changing the IENumerator LogIn() to IENumerator Start(). The program ran correctly when it was started at the beginning of a scene but not when it was triggered by a button being pressed. Weirdly, the Register() function in another script (which shares a lot of its code with this one) ran fine when triggered from a button. I'm not sure why this is.
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class Login : MonoBehaviour
{
public InputField nameField;
public InputField passwordField;
public Button acceptSubmissionButton;
IEnumerator Start()
{
WWWForm form = new WWWForm();
form.AddField("username", nameField.text);
form.AddField("password", passwordField.text);
WWW www = new WWW("http://localhost/sqlconnect/login.php", form);
Debug.Log("Form Sent.");
yield return www;
Debug.Log("Present");
if (www.text[0] == '0')
{
Debug.Log("Present2");
DatabaseManager.username = nameField.text;
DatabaseManager.score = int.Parse(www.text.Split('\t')[1]);
Debug.Log("Log In Success.");
}
else
{
Debug.Log("User Login Failed. Error #" + www.text);
}
}
public void Validation()
{
acceptSubmissionButton.interactable = nameField.text.Length >= 7 && passwordField.text.Length >= 8;
}
}
I am using angular 6 for frontend and PHP for backend (WAMP) and I want to make a login system. When someone enters valid credentials I want him to get redirected to http://localhost:4200/home
I have auth.php which sets the session variables when someone enters valid username/password and verify.php to check if the session variables are set.
Although the app redirects me to home, verify.php can not see the session variables.
Those are my files:
login-form.component.ts
loginUser(event) {
const target = event.target;
const username = target.querySelector('#username').value;
const password = target.querySelector('#password').value;
this.Auth.login(username, password).subscribe(data => {
if(data.success) {
this.router.navigate(['/home']);
}
else {
window.alert(data.message);
}
});
}
which takes the username and password from html and sends it to the service
auth.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http'
interface myData {
success: boolean,
message: string
}
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
login(username, password) {
return this.http.post<myData>('http://localhost/angular6-app/api/auth.php', {username, password},
{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}
auth.php
include 'config.php';
header('Access-Control-Allow-Origin: http://localhost:4200');
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)) {
$request = json_decode($postdata);
$username = $request->username;
$password = $request->password;
$sql = "select * from user where username = '$username'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
if($row['username'] == $username && password_verify($password, $row['password'])) //kanei verify me to hash pou exei ginei
{
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
?>
{
"success": true,
"message": "You have logged in"
}
<?php
}
else {
?>
{
"success": false,
"message": "Invalid credentials"
}
<?php
}
}
?>
and finally verify.php
<?php
session_start();
header('Access-Control-Allow-Origin: http://localhost:4200');
if (isset($_SESSION['loggedin'])) {
?>
{
"success": true,
"message": "You have the right."
}
<?php
}
else {
?>
{
"success": false,
"message": "You DONT have the right."
}
<?php
}
?>
My home.component.ts has this class and I want to display in html "You have the right" but it displays "You DONT have the right" because the variable loggedin is undefined.
export class HomeComponent implements OnInit {
message = "Loading..."
constructor(private user: UserService) { }
ngOnInit() {
this.user.getSomeData().subscribe(data => {
this.message = data.message;
})
}
getSomeData() is implemented in user.service.ts
getSomeData() {
return this.http.get<myData>('http://localhost/angular6-app/api/verify.php');
}
Is there a way to fix this problem with session or do I have to use another method of checking in angular?
Thank you.
You can't set SESSION on one domain and use on other domain, From your code it's clear you are using two different port, if you want to use sessions javascript and PHP must be on the same Domain/ports.
If you want to use different domains/ports then you have to find other ways like token based auth, i.e in auth.php after successful login create a token which will be saved in your database, send back that token in your successful response.
in your angular save that token to storage ( or wherever you prefer ) and retrieve use data from your PHP API using that token.
so when you do a call in user.service.ts your URL should contain the token
YOUR_TOKEN = '1234'//received after successfull login and saved in local storage
return this.http.get<myData>('http://localhost/angular6-app/api/verify.php?token='+YOUR_TOKEN);
in your verify.php
$token = $_GET['token'];
// check if token is valid in your database and send response
p.s when logout make sure to either expire or delete token from angulare storage and database.
You will get your session values once you build ngApp and make it live and keep your app and API in the same directory, you can use the same above method. Because you are going to access the API with same port/domain.
I had the same issue working on React and PHP locally, both using localhost but on different ports. This answer helped me.
PHP sessions are stored on cookies, and when making cross-domain (or in this case cross-port) requests those cookies are not shared.
In your first login call to PHP, you need to return the session ID using session_id() and store this somewhere on your app.
auth.php
//.....
{
"session_id": session_id(),//<- Return sid and store it on app
"success": true,
"message": "You have logged in"
}
//.....
Then, when making furter calls to PHP, make sure to pass it the same session id. You can then use session_id() again to set the id to the one you passed, which will keep the last session active:
verify.php
<?php
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)) {
$request = json_decode($postdata);
if ($request->session_id) {
session_id($request->session_id);
}
}
session_start();
header('Access-Control-Allow-Origin: http://localhost:4200');
if (isset($_SESSION['loggedin'])) {
$json['session_id'] = session_id();//Return sid and store it on your app for future calls
$json['success'] = true;
$json['message'] = "You have the right.";
} else {
$json['success'] = false;
$json['message'] = "You DONT have the right.";
}
echo json_encode($json);
I recently ran into this issue when trying to use angular-cli and xampp together. I worked around it by using
ng build
instead of
ng serve
here is build command I used.
ng build --outputPath="C:\development\xampp\htdocs\cars" --watch
This works similar to ng serve the only difference being I am serving angular app out of the xampp server instead of the angular cli server.
One more item to keep in mind is that my angular app is running inside 'cars' folder so we need to update the 'baseref' inside the index.html file in the angular application. Here is the baseref code
<base href="./">
Otherwise when we navigate to
http://localhost/cars/
it tries to pick up all the css and js files from htdocs folder
I am creating a form login with ExtJS, and sending JSON data to do authentification within Zend Framework. The problem is, no matter what username and password I fill, login always succeed. Here's the related code :
Submit Function for Ext JS Form, where we send JSON data contained username and password.
var doLogin = function () {
if (formPanel.getForm().isValid()) {
formPanel.getForm().submit({
method: 'POST',
url: '/zend/public/auth/valid',
waitMsg: 'Processing Request',
success: function (form, action) {
document.location = '/zend/public/guestbook';
},
failure: function (form, action) {
if (action.failureType = 'server') {
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Login Failed', obj.errors.reason);
} else {
Ext.Msg.alert('Warning!', 'Authentification server is uneachable : ' + action.response.responseText);
}
formPanel.getForm().reset
}
})
}
}
The Controller, we have ValidAction function to receive and send JSON data, and process to do the authentification.
public function validAction()
{
if(!isset($this->session->isLogin)){
$username = mysql_escape_string($_POST['username']);
$password = mysql_escape_string($_POST['password']);
$formdata = array('username'=>$username, 'password'=>$password);
if ($this->_process($formdata)) {
$this->session->setExpirationSeconds(3600);
$msg = '{success:true, result:{message:\'Welcome, '.$username.'!\'}}';
} else {
$msg = '{success:false, errors:{reason:\'Login failed, try again.\'}}';
}
}
protected function _process($values) {
// Get our authentication adapter and check credentials
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$user = $adapter->getResultRowObject();
$auth->getStorage()->write($user);
return true;
}
return false;
}
The problem lies in validAction, and weirdly I do var_dump to $this->process($formdata) and returns false, yet it always go to if function, message Success. Any ideas? Appreciated fellas.
UPDATE :
The var_dump :
Uncaught Error: You're trying to decode an invalid JSON String:
array(2) {
["username"]=>
string(2) "ad"
["password"]=>
string(4) "pass"
}
bool(false)
string(59) "{success:false, errors:{reason:'Login failed, try again.'}}"
Backend problem
You are outputting invalid JSON.
PHP provides json_encode to save you having to manually create json:
$response=array();
$response['success']=false;
$response['result']=array();
$response['message']='Welcome '.$username;
$msg = json_encode($response);
If you really don't want to use this you should add double quotes to your keys, and change to double quotes for your string properties too:
$msg = '{"success":true, "result":{"message":"Welcome, '.$username.'!"}}';
Front end problem
You are using success and failure methods, but I can't see anything in your back end code to send status headers.
The failure method will only get called when a response returns with a non 200 status code. So you may need to either add this to your back end code, and/or also decode the response inside your success method to make sure that you have sent success:true as part of your json before redirecting.
To send the header in PHP 5.4 or newer:
http_response_code(401);
in 5.3 or older you have to use header method instead - but if you are running this version you should upgrade immediately so I wont include an example.
I wrote a login script for a website that I am building using resources I have found online. When I ran my code on a local server it worked fine but now that I am actually running it online on a real server it doesn't work. I think I have narrowed down my error but with being new to PHP and not having prior experience with MySql I can't really fix my problem. This is the file for the login script:
//login file
<?php
class Login{
private $db_connection = null;
public function __construct(){
session_start();
$this->dologinWithPostData();
}
private function dologinWithPostData(){
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$this->db_connection()->connect_errno) {
// escape the POST stuff
$email = $_POST['email'];
// database query, getting all the info of the selected user (allows login via email address in the
// username field)
$sql = "SELECT email, password
FROM users
WHERE email = '" . $email ."'";
$result_of_login_check = $this->db_connection->query($sql);//This is 0
// if this user exists
if ($result_of_login_check->num_rows == 1) {
// get result row (as an object)
$result_row = $result_of_login_check->fetch_object();
// using PHP 5.5's password_verify() function to check if the provided password fits
// the hash of that user's password
if ($_POST['password'] == $result_row->password) {
// write user data into PHP SESSION (a file on your server)
$_SESSION['email'] = $result_row->email;
$_SESSION['user_login_status'] = 1;
} else {
$this->errors[] = "Wrong password. Try again.";
$_SESSION['user_login_status'] = 0;
}
} else {
$this->errors[] = "This user does not exist.";
}
} else {
$this->errors[] = "Database connection problem.";
}
}
print_r($this->errors);
}
public function isUserLoggedIn()
{
if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1) {
return true;
}
// default return
return false;
}
}
?>
I run it in another file that is essentially the following:
//Run file
require_once("dbconfig.php");
include_once("login.php");
$login = new Login();
if($login->isUserLoggedIn() == true){
//go to another page }
The variables used to access the database are instantiated in dbconfig.php and are correct. With this code I get an error that says the page is not working and is unable to handle the request. When I comment out the line
if (!$this->db_connection()->connect_errno) {
and the else statement following it, the output is "This user does not exist". So I think the error has something to do with $this->db_connection()->connect_errno). If you can find where I went wrong or have any advice on how to rewrite the script to make it better, it is greatly appreciated.
This is a database establishing error your live remote server database configuration is different.Please verify you dbconfig.php file make sure
database name, host , port , username , password are well defined with your live database
This is wrong:
if (!$this->db_connection()->connect_errno) {
db_connection is simply a variable containing your DB connection object. It is NOT a method.
You probably want
if (!$this->db_connection->connect_errno) {
^--note lack of ()
instead.
I think issue with this follwoing check. your result gets more than 1 records.
// if this user exists
if ($result_of_login_check->num_rows == 1) {
......
}else{
$this->errors[] = "This user does not exist.";
}
make sure your email address is unique in Data table, if it is not unique then your above statement will fail and show the text "This user does not exist." from else part
So I am trying to make a login form on my vb.net application that would connect in my mysql database via my php script. So I've set up a wampp server to test it out. Got my php code below
<?php
if($_POST)
{
if(isset($_POST["username"]) && isset($_POST["password"]))
{
$connect = mysql_pconnect("localhost","root","");
if($connect)
{
$select = mysql_select_db("ktmf",$connect);
if($select)
{
$user = mysql_escape_string($_POST["username"]);
$pwd = mysql_escape_string($_POST["password"]);
$GetRows = mysql_query("SELECT * FROM users WHERE username='$user' AND password='$pwd'");
$RowCount=mysql_num_rows($GetRows);
if($RowCount>0)
{
die("Correct !");
}
else
{
die("Incorrect !");
}
}
else
{
die("Unable to select database." . mysql_error());
}
}
else
{
die("Unable connect to database." . mysql_error());
}
}
else
{
die("Access Denied!");
}
}
else
{
die("Access Denied!");
}
?>
and then I got my vb.net code there
Imports System.Net
Imports System.Text
Public Class login
Function AuthUser(ByVal AuthenticationPage As String, ByVal Username As String, ByVal Password As String) As Boolean
Dim wc As New WebClient()
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
Dim Data As String = String.Format("username={0}&password={1}", WebUtility.UrlEncode(Username), WebUtility.UrlEncode(Password))
Dim ResponseBytes() As Byte = wc.UploadData(AuthenticationPage, "POST", Encoding.ASCII.GetBytes(Data))
Dim Response As String = Encoding.ASCII.GetString(ResponseBytes)
If Response.Contains("Correct") Then
Return True
Else
Return False
End If
End Function
Private Sub login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If AuthUser("http://127.0.0.1/login.php", TextBox1.Text, TextBox2.Text) Then
Me.Hide()
works.Show()
Else
MsgBox("You have provided invalid username or password. Unable to login.")
End If
End Sub
End Class
So when I try to login with the Application I got the Error "You have provided invalid username or password. Unable to login." wich I specified incase of error.
I still dont know what I did wrong, But if someone could help me I'd apreciate.
thanks
Your question does not contain much information, so only generaly:
1) Check what actual response (if any) you get
2) If you do not get any response, check web server log to see, if the request make it there at all
3) Test your PHP script independently on VB.NET. E.g. Simple HTML form would do.
If you share with us your findings based on above, you may get more specific answers.