AJAX live email validation (PHP) - php

When a user creates an account on my website, I want the input username to be checked against all the current usernames in my database(MySQL) and confirmed if it is available.
Does anyone know any good libraries I could use, or a plug-in for jQuery perhaps?

Exactly what you want is given in example form here. it uses jQuery as the JavaScript library

And this is untested code that is the server-side
<?php
// check_username_available.php?name=(name they supplied)
// this stuff is normally in config.inc.php
$username = "..."; // Mysql username
$password = "..."; // Mysql password
$db_name = "..."; // Database name
// get name supplied from querystring
$name = $_GET('name');
// Connect to server and select database.
//
mysql_connect("localhost", $username, $password) or die("cannot connect to db");
mysql_select_db($db_name) or die("cannot select $db_name DB");
$query = "SELECT COUNT(*) FROM 'users' WHERE user_name = '$name'";
$result = mysql_query($query) or die("cannot count rows: " . mysql_error());
header("Content-Type: text/plain");
echo ( 0 < mysql_result($result, 0) ? "false" : "true" );

Create a PHP file that takes the username as an argument. Then pass it through a $.get method in jquery. This then returns a variable (in my case called data) That variable will contain anything the PHP file printed.
$.get("ajax_available.php?u="+username, function(data){
if(data == "true")
{
// username avaiable
$("#usernameAlert").html("<img src='images/icons/accept.png'
title='Laust' /> Username available");
}
else
{
// username not avaiable
}
});
In this example my php file returns the string "true" but thats just a quick example.

Related

PHP - Access Denied while passing parameters through URL

I made a php script which'll echo an image if the correct password is entered; so that, nobody can access the images stored on my server directly, thus, making my server more secure. Now, for the php script I used GET method to generate a mysql_query to my database in order to check if the email and password entered by the user are associated with a relevant account and then echo the image from a folder on my server. Now, in order to pass the parameters while runtime, I'm adding them in the URL like this:
http://<mywebserver>/get_image.php/?email=<email>&password=<password>&file_name=<image-file-name>
But, something's wrong with this whole setup, and I'm getting the following error:
Warning: mysql_query() [function.mysql-query]: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO) in
/home/uXXXXXXXXX/public_html/get_image.php on line 11
Warning: mysql_query() [function.mysql-query]: A link to the server
could not be established in /home/uXXXXXXXXX/public_html/get_image.php
on line 11 Error getting data: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO)
Here is my php script, get_image.php:
<?php
$file_path = "/ProfilePics/";
if(isset($_GET['email']) && isset($_GET['password']) && isset($_GET['file_name'])) {
$id = "\"" . $_GET['email'] . "\"";
$typed_password = "\"" . $_GET['password'] . "\"";
$file = $_GET['file_name'];
$result = mysql_query("SELECT * FROM students WHERE email = $id AND password = $typed_password") or die ("Error getting data: " . mysql_error()); //line 11
if(!empty($result)) {
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$user = array();
$user["email"] = $result["email"];
$user["password"] = $result["password"];
$pass = "\"" . $user["password"] . "\"";
if($pass == $typed_password) {
$img_path = $file_path . $file;
echo '<img src="' . $img_path . '" name = "cover" />';
} else {
echo "Incorrect password";
}
} else {
echo "Unable to find user";
}
} else {
echo "Unable to find user";
}
} else {
echo "Required field(s) is missing";
}
?>
I agree, that there are lots of other questions already on stackoverflow stating similar problems. But, I didn't find the solution(s) to those questions applicable for my code. So, any help on this will be highly appreciated. Thank you for your time!
This is because you have not connected your file get_image.php to your MySQL database. Do so as follows:
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="database"; // Database name
$tbl_name="students"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
Simply replace the information above with the correct information.
You don't seem to be connecting to the database before you try to send queries to it.
It should like something like this:
$conn = new mysqli($servername, $username, $password, $dbname);
Taken from the example here:
http://www.w3schools.com/php/php_mysql_select.asp
Furthermore, if you care, you should consider using PDO or some other method of preventing SQL injection attacks.
SQL Injection:
https://en.wikipedia.org/wiki/SQL_injection
Information on PDO:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
setup a database connection first:
$con = mysql_connect('server','username','password');
$rst = mysql_query('select...', $con);
remember that kind of library to access mysql is outdated.
imagine someone logging in with this password:
password = '"; DROP TABLE students;'
or something crafted better.
There are different libraries like PDO or MYSQLI that take cares of this for you.
in newer releases of php standard mysql libis deprecated and removed

login page with multiple databases

I have a website that I need users to be able to login to. It is currently on a different server from the company's actual website. I would like to have a single login form that checks for a username and password in multiple databases on the same server.
Heres the setup.
1 Database has 2 different tables that I need to check for username and password.
the other database has 1 table that I need to check.
I will have a checkbox for 1 of the tables in the first database. So the form will have 3 field. (Username, Password, and "I am a reporter" checkbox)
I believe that it has something to do with the UNION sql command.
I don't know a LOT about sql but I am trying to learn as I go...
Here is the code so far.. also, I hope someone will tell me whether the information will be passed securely or not.
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['uname']) || empty($_POST['pswd'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$uname=$_POST['uname'];
$pswd=$_POST['pswd'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("company", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from dbo.contacts where WebPwd='$password' AND WebAcctName='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: "); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
It is not all complete yet and I am still researching but I am also trying to do this as quick as possible.
any help will be greatly appreciated!
It appears you make a connection declaring one name and then a different connection object name later.
$con = mysql_connect("10.0.0.3", "webaccess", "ccrweb");
$db = mysql_select_db("company", $connection);
I believe the later should use the same name $con and also at the end mysql_close($con);
First, you should use the mysqli_ or PDO API instead of mysql statements
If you need to use mysql, here is what to do:
$QueryReporter = mysql_query("SELECT * FROM $ReporterTable WHERE Username = '$Username' AND Password = '$Password'");
$QueryOthers = mysql_query("SELECT * FROM $UserTable WHERE Username ='$Username' AND Password = '$Password'");
if(mysql_num_rows($QueryReporter)==1){
//Its a reporter
}
else if(mysql_num_rows($QueryOthers)==1){
//Its not a reporter, but a user
}
else{
//Its no user or reporter, show error :)
}
EDIT:
If you are thinking about two different DB servers, you can use a function, then close the connection after the full query and return the result:
function CheckIfReporter($Username, $Password){
//DATABASE CONNECTION TO REPORTER DB
$Query = mysql_query("SELECT * FROM MyTable WHERE Username = '$Username' AND Password = '$Password'");
if(mysql_num_rows($Query)==1){
return TRUE;
}
//Else, no result:
else{
return FALSE;
}
//Close mysqlconnection:
mysql_close();
}
Now, make a similar function for user check,
if(CheckIfReporter($UsernameInput, $PasswordInput)==TRUE){
//Its a reporter
}
else if(CheckIfUser($UsernameInput, $PasswordInput)==TRUE){
//Its a user
}
else{
//Its none
}

PHP MySQL JSON Login System

I'm currently working on a login system (which works great by using two text fields and the user is then redirected). However, as I am developing a mobile app, it would be much easier to do this in JSON, and I am not entirely sure where to start. What I am basically looking to do is to use a https post request (from my app) so it would request: https://www.example.com/login.php?username=username&password=password
I have created a basic sample, but it's not what I'm looking to do with regards to passing in a parameter via the URL as my code just currently looks for users in the MySQL database and outputs the users in JSON. What I want to be able to do is pass in the username & password parameters, via the URL, and then output a "success" or "error" JSON response if the username/password is in the database or not.
<?php
$host = "localhost";
$username = "root";
$password = "password";
$db_name = "test";
$con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$sql = "select * from test_table";
$result = mysql_query($sql);
$json = array();
if (mysql_num_rows($result))
{
while ($row = mysql_fetch_row($result))
{
$json['items'] = $row;
}
}
mysql_close($db_name);
echo json_encode($json, JSON_PRETTY_PRINT);
?>
Edit
I have now started working on another system, which is pretty much what I am looking to do (after I found an example here: http://www.dreamincode.net/forums/topic/235556-how-to-create-a-php-login-with-data-from-mysql-database/) except every time that I request something like https://www.example.com/login.php?username=root&password=password - I get the JSON error 1 code
<?php
$host = "localhost"; // Host name
$db_username = "root"; // Mysql username
$db_password = "password"; // Mysql password
$db_name = "test"; // Database name
$tbl_name = "test_table"; // Table name
// Connect to server
mysql_connect("$host", "$db_username", "$db_password") or die("cannot connect");
// Select the database
mysql_select_db("$db_name") or die("cannot select DB");
// Get the login credentials from user
$username = $_POST['username'];
$userpassword = $_POST['password'];
// Secure the credentials
$username = mysql_real_escape_string($_POST['username']);
$userpassword = mysql_real_escape_string($_POST['password']);
// Check the users input against the DB.
$query = "SELECT * FROM test_table WHERE user = '$username' AND password = '$userpassword'";
$result = mysql_query($query) or die("Unable to verify user because " . mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['total'] == 1) {
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else {
// username and password not found
// failed
$response["failed"] = 1;
// echoing JSON response
echo json_encode($response);
}
?>
Try to change following lines and it should works. I get it to work, as the way you describe it.
1- Here you will get URL parameters and sanitize.
$username = $_GET['username'];
$userpassword = $_GET['password'];
$username = mysql_real_escape_string($username);
$userpassword = mysql_real_escape_string($userpassword);
2- Here you count how many rows you have
Change $row = mysql_fetch_assoc($result);
to $total_rows = mysql_num_rows($result);
3- Here you check if you have at least 1 row.
And change if ($row['total'] == 1) { to if ($total_rows == 1) {
That should give output {"success":1}
Note1: This is to solve your request and question, but does not necessary means the right approach or perfect solution in general.
Note2: I would suggest you think of password hashing, post method in stead of get, use mysqli or PDO in sted of mysql and input sensitization and not use URL to pass username and password. I would suggest you look at this link it describes some of the things I mentioned in my note1.
http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

Passing data between MySql and Objective C

I am working on a small social web application as a final project for my iOS class. I have a profile view controller where all the info about the user from the database is supposed to be displayed on the labels. The problem is that I don't really know the best way to do this. Here is my php script:
<?
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
// Create an array to hold our results
$arr = array();
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
//return the json result.
echo '{"users":'.json_encode($arr).'}';
?>
So here I get the info about all the users in the database. I am sure this is not the right way to go, so I guess I need to change the SQL query to retrieve the data for the current user only. But how can I do this? Should I put the username which I enter on the login page into an extra variable and then pass it with JSON to this php script and add the 'WHERE username = 'blabla' statement to the SQL query then? If so, how can I pass the variable to this script with JSON?
Can you please give me some sample code? Or is there a different way to do this?
Thank you so much!
<?php
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
$data = mysql_fetch_array($rs);
foreach($data as $rec){
echo "user: $rec<br>";
}
?>

Pass value from one php file to another php file

I create php file for my login.....
<?php
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$myusername=mysql_real_escape_string($_POST['uname']);
$mypassword=mysql_real_escape_string($_POST['passwd']);
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT uid FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if($row = mysql_fetch_assoc($result))
//echo mysql_result($result,0); // for correct login response
{
echo "User Found";
}
else {
echo "No Such User Found";
}
?>
It is just like this way...So here I select uid. I want get this uid & connect it to another php file. Really I want to get the details of the registered user by mapping so many tables. So I wrote the php file for that also. In the query inside that php file I want to equal the uid I get from above php file to the user_locator_tbl(the table in my database) uid. I did that. But I didn't think its correct. So pls help me.......
I gave here my other php file also....also I'm not fluent php...It is new to me...
<?php
require_once("dataget.php");
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
// Table name
$conn = mysqli_connect($host,$user,$pswd,$db);
//mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$query = "select user_master.uid,device_locator_tbl.imei,device_locator_tbl.speed,device_locator_tbl.datetime,device_locator_tbl.number,device_master.icon
from device_locator_tbl,device_master,device_registration,user_master where user_master.uid=device_registration.uid
AND device_registration.imei=device_master.imei AND device_registration.imei=device_locator_tbl.imei AND user_master.uid='$query'";
//echo ($result);
$resultarray = mysqli_query($conn,$query) or die("Unable to verify user because : " );
//if($row = mysql_fetch_assoc($result))
if($row = mysqli_fetch_assoc($resultarray))
//echo mysql_result($result,0); // for correct login response
{
$rows[] = $row;
}
// close the database connection
mysqli_close($conn);
// echo the application data in json format
echo json_encode($rows);
?>
First off, you should use prepared statements, the mysql_ functions are deprecated in PHP and create a real issue for SQL injection, particularly in a login.
But using your example, refer to: PHP Login & MySql Query
The questioned code & answer there is perfectly pertinent to what you have thus far, and a simple, vastly more secure way to accomplish everything you need:
The original posters script you see is meant to store the users info into a $_SESSION[] array, from the database query like you have. Once the login attempt is validated the header(location:) call that you see in the original questions code will redirect the user to the location required.
Once the user is redirected, all the information from your user table query will be stored in the $_SESSION array and from then on accessible like $_SESSION[loggedinuser][userid], $_SESSION[loggedinuser][email] etc.
Remember to configure your PHP install appropriately for destroying sessions via a timeout, and also consider a logout function to destroy the user session.
So you should edit your first page like this ONLY IF you are NOT/CANNOT switching over to PDO - remember if you use sessions you should start session on page top:
<?php
session_start();
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$myusername=mysql_real_escape_string($_POST['uname']);
$mypassword=mysql_real_escape_string($_POST['passwd']);
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT uid FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if($row = mysql_fetch_assoc($result))
//echo mysql_result($result,0); // for correct login response
{
$_SESSION['uid'] = $row['uid'];
header("Location: nextpage.php");
//echo "User Found";
}
else {
echo "No Such User Found";
}
?>
And You can catch this value from next page like this:
<?php
session_start();
// this section validate your inner files no one can enter this file without login
if(empty($_SESSION['uid'])){
header("Location: index.php");
}
// now you can do whatever you like
echo $_SESSION['uid'];
require_once("dataget.php");
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
// Table name
$conn = mysqli_connect($host,$user,$pswd,$db);
//mysql_select_db($db, $conn);
//run the query to search for the username and password the match
//$query = "SELECT * FROM "." ".$tbl_name. " "."WHERE uname = '$myusername' AND passwd= '$mypassword' ";
$query = "select user_master.uid,device_locator_tbl.imei,device_locator_tbl.speed,device_locator_tbl.datetime,device_locator_tbl.number,device_master.icon
from device_locator_tbl,device_master,device_registration,user_master where user_master.uid=device_registration.uid
AND device_registration.imei=device_master.imei AND device_registration.imei=device_locator_tbl.imei AND user_master.uid='$query'";
//echo ($result);
$resultarray = mysqli_query($conn,$query) or die("Unable to verify user because : " );
//if($row = mysql_fetch_assoc($result))
if($row = mysqli_fetch_assoc($resultarray))
//echo mysql_result($result,0); // for correct login response
{
$rows[] = $row;
}
// close the database connection
mysqli_close($conn);
// echo the application data in json format
echo json_encode($rows);
?>

Categories