Posting form data from VB.NET to PHP script - php

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.

Related

Send data from unity3d game to PHP empty variables

I want to send data from my game to the Database on the server. In this case, I develop locally but when I click the spacebar button The Database is created but With empty data. No data is sent from my game.
I have to try to improve my code also try to implement the pre statements.
I am not able to use the unitywebrequest because my version of UNITY3D does not have it my version is 5.0.0f4
When I try to insert the data by hand on fields in the editor and then start the preview, and click the spacebar to send the data, but when I click the database create a row but with empty data, what I fail here, can't find the problem
Also, i have aply the debug.log to see if there is any info send from my app to the script and the data is there but i continue not understand why is my code not work correctly, i also provide the prints of the app and database.
I also edit again to make the password hash changes i just did but i dont know if is correct like this
!https://imgur.com/J5R56Xf
!https://imgur.com/pzd7t4e
!https://imgur.com/x9VRK6P
This is my unity code below.
using UnityEngine;
using System.Collections;
public class DataInserter : MonoBehaviour {
public string inputUserName;
public string inputPassword;
public string inputEmail;
public string regdata;
string CreateUserURL = "localhost/InsertUser.php";
// Use this for initialization
void Start () {
//regdata = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Space)) CreateUser(inputUserName, inputPassword, inputEmail, regdata);
}
public void CreateUser(string username, string password, string email, string regdata){
WWWForm form = new WWWForm();
form.AddField("usernamePost", username);
form.AddField("passwordPost", password);
form.AddField("emailPost", email);
form.AddField("regdataPost", regdata);
WWW www = new WWW(CreateUserURL, form);
}
}
And This is my New PHP code below.
//Variables for the connection
$servername = "localhost";
$server_username = "root";
$server_password = "mysql";
$dbName = "wizard2019";
$saveuser = "INSERT INTO users (username, email, password, regdata)
VALUES ('".$username."','".$email."','".$password."','".$regdata."')";
//Variable from the user
$username = $_POST["usernamePost"];
$email = $_POST["emailPost"];
$password = password_hash($_POST["passwordPost"], PASSWORD_DEFAULT);
$regdata = $_POST["regdataPost"];
//$username = "helder";
//$email = "test email";
//$password = "123456";
//$regdata = "20201123";
//Make Connection
$conn = new mysqli($servername, $server_username, $server_password, $dbName);
//Check Connection
if(!$conn){
die("Connection Failed. ". mysqli_connect_error());
}
$sql = $saveuser;
$result = mysqli_query($conn ,$sql);
if(!$result) echo "there was an error";
else echo "Registration Sucessfull";
?>
First of all WWW class has been obsolete. Look at this docs of unity here.
Also you need to use 'Coroutine' to wait until you get a response from WWW. See the code below:
void Start () {
string url = "http://www.example.com/";
WWW www = new WWW(url);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
Debug.Log("Success: " + www.data);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
Check this amazing tutorial of Unity with PHP MySQLi here if you really want to stick with your approach.
I recommend you to use UnityWebRequest to POST or GET data. See this official docs here.
For Example:**
IEnumerator Upload()
{
WWWForm form = new WWWForm();
form.AddField("myField", "myData");
using (UnityWebRequest www = UnityWebRequest.Post("http://www.my-server.com/myform", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
}

What is Causing my Code to Not Return Any Data When Trying to Send a Login Request to a Local Server?

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;
}
}

How do I run a php script on Angular on input change?

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?

Login script issue with database

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

How do I sync my users connections PHP

I have a class in PHP called cUser:
class cUser {
var $m_email;//The users email adresse(String)
var $m_password;//His password(String)
var $m_username;//His username(String)
var $m_active;//If the user have been activate (By following a link send to him via is email)(Bool)
function __construct($p_username, $p_password, $p_email, $p_active) {
$this->m_username = $p_username;
$this->m_password = $p_password;
$this->m_email = $p_email;
$this->m_active = $p_active;
}
//this is the important part...
function connexion() {
include "Config.php";//include all the parameters needed to connect to the DB
$cn = new cConnexion($ConnexionDBHost, $ConnexionDBName, $ConnexionDBLogin, $ConnexionDBPassword);//Initiate a connection to the DB
if($cn->DBConnexion())//If it is connected {
$parameters = array('username'=>$this->getUsername(), 'password'=>$this->getPassword());//create an array with the username and the password
$getConnexion = $cn->SecureSelect("SELECT username, password, email, active FROM user WHERE BINARY username = :username AND BINARY password = :password", $parameters);//selecte the user in the DB (for DB description see below code)
if($getConnexion != null) { //if there is no error in the query.
$resultSet = $getConnexion->fetch();//fetch the results
if($resultSet != null) { //if there is a match
//assigne the DB field values to this instance of cUser
$this->setUsername($resultSet['username']);
$this->setPassword($resultSet['password']);
$this->setEmail($resultSet['email']);
$this->setActive($resultSet['active']);
if($this->getActive() == 1) {
//If the user has been activate already return success
}
else {
//Else send an activation email to the user.Dont connecte him and return an error message
}
}
else {
//Send an error message
}
}
else {
//send an error message
}
}
else {
//send an error message
}
}
//this are not important for the question but I put them there so you can see what kind of operation the class is doing.
function delete(){//Delete this instance of cUser from de DB}
function insert(){//Insert this instance of cUser from the DB}
function update($p_email, $p_username, ...){//Update this instance of cUser with the new parameters}
function activateAccount(){//Activate this instance of cUser}
//And all the getters and setters associate with the class attributes.
}
Here is the MySQL Table containing the field for the cUser class (roughly coded):
USER
varchar email,
varchar password,
varchar username,
tiny int activate,//1 or 0
tiny int connected//1 or 0
Question:
How can I implement or change the function connection so one instance of a user is connected at the same time?
Note:
I already know I can just check if the DB connected field is set to 1 but if two user access the DB at the same time it would create a problem (race condition or something like that).
Is there something like a mutex or semaphore I can use to sync the access of the DB field connected??
Example:
David fill the HTML form and submit it with user name and password ("Dav1", "ThisIsPassword"), a process page create the cUser instance and connect to check if Dav1 already existe then give him access to the rest of the web-app.
Now Davos fill the form and submits it with the same user-name and password that David used because Davos and David are friend and they shared the same account and shared there password.
With the existing code both David and Davos can then access the web application at the same time with the same account what I want is that when David connect Davos get an error message that tell him that the user is either already connected or the user-name/password doesn't match.
Use a transaction.
In MySql you can also use SELECT FOR UPDATE statement.
Pseudocode:
$transaction = db->beginTransaction();
try {
$user = User::getByUsername($username);
if ($passwordImcorrect)
throw new Exception('invalid credentials');
if (user->loggedIn)
throw new Exception('already logged in');
user->loggedIn = 1;
user->save();
$transaction->commit();
}
catch (Exception $e) {
echo $e->getMessage();
$transaction->rollback();
}

Categories