here is the case guys, I'm trying to check username on onblur event with help of ajax , which is checking username availability in mysql database.
here is ajax script =>
document.getElementById("r_username").onblur = function(){
var http = false;
var error = document.getElementById("error_username");
var numLetter = /^[a-zA-Z-0-9]+$/;
if (this.value==""){
error.innerHTML = "Empty Field !!!";
error.style.display = "inline";
} else {
if (this.value.match(numLetter)){
if (window.XMLHttpRequest){
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
if (http){
http.open("POST","./config/AjaxUsernameEmail.php",true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(){
if (http.readyState==4 && http.status==200){
}
};
http.send("r_username=" + document.getElementById("r_username").value);
}
error.innerHTML = "";
error.style.display = "none";
} else {
error.innerHTML = "Invalid Number !!!";
error.style.display = "inline";
}
}
};
ajax working successfully and .php file too which script is below =>
class Checking{
private $con,$query,$flag;
public function __construct($con,$query){
$this->con = $con;
$this->query = $query;
}
public function func(){
if (mysqli_connect_errno()==0){
if ($result = mysqli_query($this->con,$this->query)){
if ($data = mysqli_fetch_assoc($result)){
return $this->flag = true;
} else {
return $this->flag = false;
}
}
}
}
}
if (isset($_POST['r_username'])){
$check = new Checking($connection,"SELECT username FROM users WHERE username='" . $_POST['r_username'] . "'");
} else {
header("Location: http://" . $mysql->host . "/index.php");
}
everything is working just fine , but here is the problem , i want to connect somehow this files , I mean that I want to know in .js file when username is matching in database and when not , because I want to do more action in .js file , but I can not set "flag" (variable which will help me for that).
Any ideas ? thanks :)))
In more details , .js file is in registration.php file , and how you can see guys .js file is invoking with ajax AjaxUsernameEmail.php file, so I want to do somehow to know when username is matching and when not , because I want in registration.php file to do more actions (notifications) during matching
The code could be a bit more like so:
$return = 'fail';
class Checking {
public function __construct($con, $query)
{
$this->con = $con;
$this->query = $query;
self::func()
}
public function func()
{
$result = 'ok';
if (mysqli_connect_errno()==0){
if ($result = mysqli_query($this->con,$this->query)){
$result = mysqli_num_rows($result) > 0? 'user_exists' : 'user_doesnt_exist';
}
}
return $result;
}
}
if( $_POST['r_username'] ){
$desired = mysqli_real_escape_string($_POST['r_username']);
$return = new Checking($connection,"SELECT username FROM users WHERE username='$desired'");
}
echo $return;
Also, you should be worried about escaping user input, and may want to look into jQuery for your ajax stuff.
The checking on the client side, should go something like this:
if (http.readyState==4 && http.status==200){
switch (http.responseText){
case 'fail':
//the username was not provided
break;
case 'user_exists':
//the username already exists
break;
case 'user_doesnt_exist':
//the username was not found on the database, continue
break;
}
}
For ajax request you must not return the value but print or echo it. Try
if ($data = mysqli_fetch_assoc($result)){
echo $this->flag = true; exit;
} else {
echo $this->flag = false; exit;
}
Evaluationg response:
if ( http.readyState == 4 && http.status == 200 ) {
switch ( http.responseText ) {
case 1: //user name taken, diplay error message
break;
case 0: //user name available, no action required
break;
}
}
Related
So im using the exact same script as I used to a while back and for some reason when I move to my new domain and hosting it is having really weird issues, I created a user and got hm to try login, It wasnt working for him I got a new hash from a random test.php file with this php:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>
It then worked, He logged in fine and I then tried to login to my main admin account and for some reason its now not working even when I try remaking the hash 2 times now.
I have no idea whats going on can someone please enlighten me.
Heres the login code:
//If User Submits Form continue;
if(isset($_POST['username'])) {
//If the captcha wasn't submitted;
if(empty($_POST['g-recaptcha-response'])) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
}
//If the captcha was submitted;
} else {
//Set captcha variable to the Submitted Captcha Response;
$captcha=$_POST['g-recaptcha-response'];
//Captcha Verification Url;
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';
//JSON Encode the Captcha's response and Site IP;
$response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);
//If the captcha wasn't verified;
if($response['success'] == false) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
}
//Otherwise if it was verified;
} else {
//Try log in with the given details;
user_login($_POST['username'],$_POST['password']);
//If logged in redirect and give a notification;
if(loggedin()) { ?>
<script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
<meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
} else {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
}
}
}
}
}
User_login function:
//Create a new function named user_login;
function user_login($username = false, $password = false) {
//Fetch for the username and password applied;
$st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));
//If a row was found continue
if($st != 0) {
$storedhash = $st[0]['password'];
if (password_verify($password, $storedhash)) {
//Set a new username session and set it the username;
$_SESSION['username'] = $username;
$_SESSION['email'] = $st[0]['email'];
$_SESSION['image'] = $st[0]['image'];
if($username == 'admin') {
$_SESSION['role'] = 'admin';
} else {
$_SESSION['role'] = 'user';
}
}
}
//If no errors happened Make the $valid true;
return true;
$dontaddtry = true;
}
Fetch function:
//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {
//Prepare The SQL Query;
$query = Connect()->prepare($sql);
//Execute Binded Query;
$query->execute($bind);
//While Fetching Results;
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
//Add a row to the results respectiveley;
$row[] = $result;
}
//If there are no rows;
if(!empty($row)) {
//Make it an object;
$row = ($obj)? (object) $row : $row;
} else {
//Else row is false;
$row = false;
}
//If no errors happened Make $row true;
return $row;
}
Connect Function:
//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {
//Try execute the PHP with no errors;
try {
//Create a PDO Session;
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//Session Attributes;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
//Catch all PDOException errors;
catch (PDOException $e) {
//If any errors print result;
echo "<code><pre>".print_r($e)."</pre></code>";
//Make the PDO session false;
$con = false;
}
//If no errors happened Make the PDO session true;
return $con;
}
P.S If you wish to get an account to try on my site let me know and ill make a temporary account.
Make sure your the php version of your new hosting. password_hash needs at-least PHP 5.5.0.
You can check your current PHP version via following code.
<?php
echo 'Current PHP version: ' . phpversion();
?>
I have build a small website with some php. It works perfectly on my localhost (even without database information it loads the html and css).
However when I put it online I just get a blankpage, no errors, nothing. However when I manually type a page it redirects to the login page (which is good).
Anyone experienced this before?
Thanks
EDIT2: After some debugging advice I got this error
Warning: include_once(classes/users.class.php): failed to open stream:
No such file or directory in
/customers/c/2/9/nicolasdecroos.be/httpd.www/eindwerk/login.php on
line 8 Warning: include_once(): Failed opening
'classes/users.class.php' for inclusion
(include_path='.:/usr/share/php') in
/customers/c/2/9/nicolasdecroos.be/httpd.www/eindwerk/login.php on
line 8 Fatal error: Class 'user' not found in
/customers/c/2/9/nicolasdecroos.be/httpd.www/eindwerk/login.php on
line 9
Edit: Here is the PHP code on the login page
<?php
session_start();
include_once("classes/users.class.php");
$user = new user();
if(isset($_SESSION['loggedin']))
{
header('location: index.php');
}
else
{
if(!empty($_POST))
{
try
{
$user->login($_POST['studentennummer'],$_POST['password']);
}
catch (Exception $error)
{
$message = $error->getMessage();
}
}
}
?>
This is users.class
*Sorry if it's to much code, I'm not sure which part would be the most interesting.
<?php
include_once("classes/db.class.php");
class user
{
private $m_sStudentennummer;
private $m_sPassword;
private $m_sStatus;
public function __get($p_sProperty)
{
switch ($p_sProperty)
{
case 'Studentennummer':
return $this->m_sStudentennummer;
break;
case 'Password':
return $this->m_sPassword;
break;
case 'Status':
return $this->m_sStatus;
break;
}
}
public function __set($p_sProperty, $p_vValue)
{
switch ($p_sProperty)
{
case 'Studentennummer':
$this->m_sStudentennummer = $p_vValue;
break;
case 'Password':
$this->m_sPassword = $p_vValue;
break;
case 'Status':
$this->m_sStatus = $p_vValue;
break;
}
}
public function userCheck($p_sInput)
{
$db = new db();
$sql = "SELECT * FROM users WHERE u_id = '". $p_sInput . "'";
$result = $db->conn->query($sql);
if ($result->num_rows == 0)
{
return "true";
}
else
{
return "false";
}
}
public function login($p_sStudentennummer, $p_sPassword)
{
$db = new db();
$sql = "SELECT * FROM users WHERE u_nr = '".$db->conn->real_escape_string($p_sStudentennummer)."' AND u_pass = '".$db->conn->real_escape_string($p_sPassword)."';";
$result = $db->conn->query($sql);
$rows = $result->fetch_assoc();
$status = "SELECT * FROM users WHERE u_nr = '".$db->conn->real_escape_string($p_sStudentennummer)."' AND u_pass = '".$db->conn->real_escape_string($p_sPassword)."' AND u_group = 'student'";
$statusRes = $db->conn->query($status);
if ($result->num_rows == 1)
{
if ($statusRes->num_rows == 1)
{
$_SESSION['u_id'] = $rows['u_id'];
$_SESSION['loggedin'] = 1;
header('Location: index.php');
}
else
{
$_SESSION['u_id'] = $rows['u_id'];
$_SESSION['loggedin'] = 1;
header('Location: my_events.php');
}
}
else
{
throw new Exception("Username and/or password are invalid.");
}
}
}
?>
Change the error level for the online hosting if you can.
It will display every errors on the screen, but is very useful (for me at least).
<? error_reporting(E_ALL); ?>
Alright,
It was something dumb but I'll post it incase someone has troubles with this.
The map was called "Classes". in the code it was written as "classes".
On localhost it wasn't a problem, but when you put it online it is.
Ok, so when I execute the initial function it works fine, the username gets stored in the database, however when I run the second function that appends the username to the text the user chooses to enter the IF statement returns 'no user' - when a user is defined...
If anyone knows how to fix this that would be great - I am currently learning PHP and mysql so I am sorry if any of this is incorrect
<?php
session_start()
// connect to the database
mysql_connect("localhost", "root", "");
mysql_select_db("ajaxchat");
// read the stage
$stage = $_POST['stage'];
// primary code
if($stage == 'initial') {
// check the username
$user = $_POST['user'];
$query = mysql_query("SELECT * FROM chat_active WHERE user='$user'");
if (mysql_num_rows($query) == 0) {
$time = time();
//
mysql_query("INSERT INTO chat_active VALUES ('$user', '$time')");
// set the session
$_SESSION['user'] = $user;
echo 'good';
}
else {
echo 'taken';
}
}
/////////////// PROBLEM FUNCTION ///////////////
================================================
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
// check for user_error
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
}
}
else {
echo 'error';
}
?>
This is the javascript:
<script type="text/javascript">
function chat_initialise() {
var user = document.getElementById("chat_user").value;
$.post("./chat.php", {stage:"initial", user:user}, function(data) {
if (data == "good") {
$('#initial').css('display', 'none');
$('#content').css('display', 'inline')
}
else {
alert("That username is taken! Please try another.");
}
});
}
function chat_send() {
var text = document.getElementById("chat_text").value;
$.post("./chat.php", {stage:"send", text:text}, function(data) {
document.getElementById("chat_text").value = '';
$('#window').text($('#window').text() + data);
// alert(data)
});
}
</script>
I fixed it - changed the POST function to take the current username then redefine it as a variable in the second function:
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
$user = $_POST['user'];
echo $user;
// check for user_error
if (isset($_SESSION['user'])) {
$_SESSION['user'] = $user;
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
var_dump($_SESSION);
}
}
Thanks for all your help guys!!
I'm currently building a system for a football league. And are currently working on the script file for adding results. Most of the script works and the result is always successfully added to the database. However the authentication part seems to fail. The if statement on line 12 does not seem to fire and I can't understand why.
My code can be found in the pastebin link here: http://pastebin.com/ty4pdGgn
<?PHP
include 'functions.php';
dbConnect();
//$userEmail = mysql_real_escape_string($_POST["userEmailText"]);
$userCode = mysql_real_escape_string($_POST["userPasscodeText"]);
$authenticated = false;
$userEmail = "info#example.com";
if ($userEmail == "info#example.com") {
header('Location: ../results.php?error=authentication');
}
$allUsers = mysql_query("SELECT * FROM accounts WHERE email = '$userEmail'");
while ($thisUser = mysql_fetch_assoc($allUsers)){
if ($userCode != $thisUser['passCode']) {
header('Location: ../results.php?error=authentication2');
}
echo $thisUser['passCode'];
$authenticated = true;
$userID = $thisUser['userID'];
}
if (!$authenticated) {
header('Location: ../results.php?error=authentication3');
}
$dateSubmitted = $_POST['submissionDate'];
$homeTeam = $_POST['homeTeam'];
$awayTeam = $_POST['awayTeam'];
$homeGoals = $_POST['homeGoals'];
$awayGoals = $_POST['awayGoals'];
if ($homeTeam == $awayTeam) {
header("Location: ../results.php?error=team");
}
if (getTeamLeague($homeTeam) != getTeamLeague($awayTeam)) {
header("Location: ../results.php?error=league");
} else {
$leagueID = getTeamLeague($homeTeam);
}
if ($homeGoals > $awayGoals) {
$winnerID = $homeTeam;
} else if ($homeGoals < $awayGoals) {
$winnerID = $awayTeam;
} else if ($homeGoals == $awayGoals) {
$winnerID = -1;
}
$cQuery = mysql_query("INSERT INTO results VALUES ('', $userID, '$dateSubmitted', $leagueID, $homeTeam, $homeGoals, $awayTeam, $awayGoals, $winnerID, 0)");
if ($cQuery){
header('Location: ../results.php');
} else {
echo mysql_error();
}
?>
Any help with this matter will be much appreciated. The functions.php contains no errors as this is all to do with database entry and not the authentication.
Put a die(); after the header("Location:...");
As your comparison code (the "if" part on line 12) that you pasted has to work, i have two advice:
Put a die(); or exit(); after the header() part.
Try looking here, as I am not sure if header() will work, while the location path you set is relative. Basic advice is to always use base paths for redirects, like "http://your.site.com/script.php").
So, I have 3 forms on the same page and same controller action, when I click on one of the submit button, it validates all forms instead of the one I clicked.
how can I separate it from validation??
here my code:
public function signUpAction()
{
$firstName = $this->getRequest()->getParam('firstName');
$lastName = $this->getRequest()->getParam('lastName');
$email = $this->getRequest()->getParam('email');
$emailAdrress = $this->getRequest()->getParam('Email_Address');
$password = $this->getRequest()->getParam('password');
$signupForm = new Application_Form_UserSignUp();
$loginForm = new Application_Form_UserLogin();
$retreivePasswordForm = new Application_Form_UserRetreivePassword();
if ($this->getRequest()->isPost('signupForm'))
{
/*********** Sign Up Form ***********/
if ($signupForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($signupForm->getValues());
if ($user->save())
{
Zend_Session::rememberMe(186400 * 14);
Zend_Auth::getInstance()->getStorage()->write($user);
$user->sendSignUpEmail();
$this->getHelper('redirector')->gotoRoute(array(), 'invite');
return;
}
else
{
}
}
else
{
// something
}
}
if ($this->getRequest()->isPost('loginForm'))
{
/************ Login Form ************/
if ($loginForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($loginForm->getValues());
$user = $this->_helper->model('Users')->fetchRowByFields(array('email' => $email, 'hash' => $password));
if($user)
{
Zend_Session::rememberMe(86400 * 14);
Zend_Auth::getInstance()->getStorage()->write($user);
$this->getHelper('redirector')->gotoRoute(array(), 'invite');
return;
}
else {
// Error message
$this->view->errorMsg = "<b>password</b> - invalid, please try again! *";
}
}
else
{
// something
}
}
if ($this->getRequest()->isPost('retreivePasswordForm'))
{
/****** Retreive Password Form ******/
if ($retreivePasswordForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($retreivePasswordForm->getValues());
$user = $this->_helper->model('Users')->fetchRowByFields(array('email' => $emailAdrress));
if($user)
{
Zend_Auth::getInstance()->getStorage()->write($user);
$user->sendRetreiveEmail();
$_SESSION['email'] = $emailAdrress;
$redirector = $this->_helper->getHelper('redirector');
$redirector->setCode(301)->setUseAbsoluteUri();
$newPath = 'http://refer.lavasoft.com/#retreive_sent';
$redirector->gotoUrl($newPath);
//$this->view->assign('sendEmail', $emailAddress);
}
else
{
}
}
else
{
// something
}
}
$this->view->retreivePasswordForm = $retreivePasswordForm;
$this->view->loginForm = $loginForm;
$this->view->signupForm = $signupForm;
}
This is not how it works in ZF. You cannot pass the form name to isPost() unless you override isPost() in your code.
What you could do is Define all your fields like:
loginForm[name]
loginForm[password]
and
signupForm[name]
etc
then just check for isset($_POST['loginFom'])
This should work fine.
Or use a hidden field named formName and check in your code what's its value is.
You can also use a different action for each form and in the end redirect to the signUpAction wich would yeld the same result without the hassle.