So I have a problem with my registration and login php code. I have put them together in one php file called index.php and the registration works fine but when i try to login it clashes with the registration statements.
<?php
include_once("php_includes/check_login_status.php");
// If user is already logged in, header that weenis away
if($user_ok == true){
header("location: user.php?u=".$_SESSION["username"]);
exit();
}
?>
<!-- .registerphp -->
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_conx.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?>
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
include_once ("php_includes/blowfish.php");
$cryptpass = crypt($p);
$p_hash = cryptPass($cryptpass)."$cryptpass".cryptPass($cryptpass);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#pfolio.bugs3.com";
$subject = 'PFolio Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>PFolio Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.pfolio.bugs3.com/images/smalllogo.png" width="215" height="50" alt="PFolio" style="border:none; float:left;">PFolio Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* Username: <b>'.$u.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
<!-- .registerphp -->
<!-- .loginphp -->
<?php
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE
$u = mysqli_real_escape_string($db_conx, $_POST['u']);
$p = crypt($_POST['p']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// FORM DATA ERROR HANDLING
if($u == "" || $p == ""){
echo "login_failed";
exit();
} else {
// END FORM DATA ERROR HANDLING
$sql = "SELECT id, username, password FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if($p != $db_pass_str){
echo "login_failed";
exit();
} else {
// CREATE THEIR SESSIONS AND COOKIES
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE);
// UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
}
}
exit();
}
?>
<!-- .loginphp -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<title>P'Folio</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="css/loginstyle.css" rel="stylesheet" type="text/css">
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<!-- .registerjs -->
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
</script>
<!-- .registerjs -->
<!-- .loginjs -->
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function login(){
var u = _("user_name").value;
var p = _("pass_word").value;
if(u == "" || p == ""){
_("sta_tus").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("sta_tus").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
_("sta_tus").innerHTML = "Login unsuccessful, please try again.";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("u="+u+"&p="+p);
}
}
</script>
<!-- .loginjs -->
</head>
<body>
<!-- .wrapper -->
<div class="wrapper">
<!-- .header-->
<header class="header"> <img src="images/logo.png" alt="logo" title="P'Folio"> </header>
<!-- .header-->
<!-- .login -->
<div class="login">
<form id="loginform" onsubmit="return false;">
<div><img class="h1" src="images/lh.png" alt="login%20here"/></div>
<div><img class="p1" src="images/wb.png" alt="welcome%20back"/></div>
<input type="text" id="user_name" onfocus="emptyElement('status')" maxlength="16" class="loginboxes" placeholder="Username">
<input type="password" id="pass_word" onfocus="emptyElement('status')" maxlength="100" class="loginboxes" placeholder="Password">
<br />
<button id="loginbtn" onclick="login()">Log In</button>
<p id="sta_tus"></p>
Forgot Your Password?
</form>
</div>
<!-- .login -->
<!-- .main -->
<main class="content">
<p>Are you a musician, a model, actor or actress or anyone with a talent then sign up for P'Folio.
Here on P'Folio we look to give you space to upload a portfolio for you to be noticed. </p>
</main>
<!-- .main -->
<!-- .signup -->
<div class="signup">
<form name="signupform" id="signupform" onsubmit="return false;">
<div><img class="h1" src="images/caa.png" alt="create%20account"/></div>
<div><img class="p1" src="images/ntm.png" alt="new%20to%20P'Folio"/></div>
<span id="unamestatus"></span>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16" placeholder="Username" class="registerboxes">
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88" placeholder="Email" class="registerboxes">
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="100" placeholder="Password" class="registerboxes">
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="100" placeholder="Confirm Password" class="registerboxes">
<select id="gender" onfocus="emptyElement('status')" class="registerboxes">
<option value="0" selected="selected">Choose...</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<select id="country" onfocus="emptyElement('status')" class="registerboxes">
<?php include_once("template_country_list.php"); ?>
</select>
<div class="conditions">By clicking Sign Up,
you agree to our Terms and that
you have read our Privacy Policy ,
including our Cookie Use .</div>
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
<!-- .signup -->
<!-- .footer -->
<footer class="footer">
<div id="legal"><a class="legal" href="JavaScript:newPopup('Login/Legal/Terms.php');">Terms</a> | <a class="legal" href="JavaScript:newPopup('Login/Legal/Privacy.php');">Privacy</a></div>
<div id="font"><a class="font">P'folio © 2014</a></div>
</footer>
<!-- .footer -->
</div>
<!-- .wrapper -->
</body>
</html>
Why is my Registration and Login code not working?
For registration and also login don't use AJAX. It is better. You may use classic JavaScript for pre-checking of correct setting of username and password, but don't use AJAX for own login and registration process.
Also it is good to split both processes into different places. I have not ever seen any web where login and registration would be done from the same place - and via AJAX.
For username checking you may use order
preg_match('/^[^0-9][a-z0-9]{3,16}/i', $_POST['username']);
that checks if username does not start with number and is long at least 3 signs and not longer than 16 signs. Also it allows small letters and numbers.
Related
First of all I must say that I'm very new to website design and coding so please make your answer simple thanks a lot .
So I have my file register.php that contains my form .
I have my action file named register-controller.php that gets the data from user , checks it and inserts it to database .
What I need is that whenever the register is success , my form gets hidden or removed and my new div shows up that contains 'register successful' . ( On the same page "register.php" )
Can I use the variable that I passed to header "register=success" to do this action ? Should I use AJAX ? JSON ? what should I do ? Please give me the simplest answer thank you all .
MY "register.php" file contains these :
<?php
require_once "../DB/users-database.php";
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/Header.CSS">
<link rel="stylesheet" href="/Style.CSS">
<link rel="stylesheet" href="/Footer.CSS">
<script src="https://kit.fontawesome.com/38b3678073.js" crossorigin="anonymous"></script>
<script src="../JS/main.js" async></script>
<title>ثبت نام | PCGA</title>
</head>
<body>
<?php include '../header.php' ?>
<div class="register-container">
<form action="../controllers/register-controller.php" method = "POST">
<label class = "email-label" for="email">ایمیل</label>
<input type="text" id="email" name="email" placeholder="example#example.com" value = '<?php if(isset($_REQUEST['email'])){echo $_REQUEST['email'];}else{echo '';} ?>'>
<?php
if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyEmail'){
echo "<span class = 'empty-email'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidEmailFormat') {
echo "<span class = 'formaterr-email'>فرمت ایمیل نادرست است*</span>";
}
?>
<label class = "phone-label" for="phone">شماره موبایل</label>
<input type="text" id="phone" name="phone" placeholder="09xxxxxxxxx" value = '<?php if(isset($_REQUEST['phone'])){echo $_REQUEST['phone'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPhone'){
echo "<span class = 'empty-phone'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidPhoneNumber') {
echo "<span class = 'formaterr-phone'>شماره موبایل حداکثر 11 عدد است و حروف قابل قبول نیست*</span>";
}
?>
<label class = "user-label" for="username">نام کاربری</label>
<input type="text" id="username" name="username" placeholder="Username" value = '<?php if(isset($_REQUEST['username'])){echo $_REQUEST['username'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyUsername'){
echo "<span class = 'empty-user'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidUserName') {
echo "<span class = 'formaterr-user'>فرمت نام کابری نادرست است*</span>";
}
?>
<label class="pass-label" for="password">رمز عبور</label>
<input type="password" id = "password" name = "password" placeholder = "Password" >
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPass'){
echo "<span class = 'empty-pass'>فیلد نباید خالی باشد *</span>";
}
?>
<div class="checkbox-container">
<input type="checkbox" class = 'checkbox-style' name = 'rules-check'>
<label for="checkbox" class="checkbox-label">من قوانین فروشگاه را کامل مطالعه کرده ام و با آن موافق هستم</label>
<?php if (isset($_REQUEST['rules'])){
echo "<span class = 'rules-error'>قبول قوانین اجباری است و آن را حتما مطالعه کنید *</span>";
}
?>
</div>
<button type="submit" name = "submit" id="submit">ثبت نام</button>
</form>
</div>
<?php
if (isset($_REQUEST['register'])){
echo "<div class = 'register-success'>
<span class = 'register-success-span'>ثبت نام با موفقیت انجام شد</span>
</div>" ;
}
?>
<?php include '../footer.php' ?>
</body>
</html>
MY "register-controller.php" file contains these :
<?php
require "../DB/users-database.php";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['submit']) && $_POST['rules-check']) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
if (empty($username)){
header("Location: ../page/register.php?error=emptyUsername&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($phone)){
header("Location: ../page/register.php?error=emptyPhone&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($pass)){
header("Location: ../page/register.php?error=emptyPass&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($email)){
header("Location: ../page/register.php?error=emptyEmail&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (!filter_var($email , FILTER_VALIDATE_EMAIL)) {
header("Location: ../page/register.php?error=invalidEmailFormat&username=".$username."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[a-z\d_]{2,20}$/i" , $username)){
header("Location: ../page/register.php?error=invalidUserName&email=".$email."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[0-9]{11}+$/" , $phone)){
header("Location: ../page/register.php?error=invalidPhoneNumber&email=".$username."&phone=".$phone);
exit();
}
else {
$sql = "SELECT username FROM registered WHERE username = ?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLcheckUser");
exit();
}
else {
mysqli_stmt_bind_param($stmt , "s" , $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$rowcount = mysqli_stmt_num_rows($stmt);
if($rowcount > 0 ) {
header("Location: ../page/register.php?error=UserNameTaken");
exit();
}
else {
$sql = "INSERT INTO registered(email,phone,username,password) VALUES(?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLInsert");
exit();
}
else {
$hased_pass = password_hash($pass , PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt , "ssss" , $email , $phone , $username , $hased_pass);
mysqli_stmt_execute($stmt);
header("Location: ../page/register.php?register=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
elseif (isset($_POST['submit']) && !isset($_POST['rules-check'])) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
header("Location: ../page/register.php?rules=notChecked&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
else {
header("Location: ../page/register.php?access=denied");
exit();
}
?>
You can render the part of the page you prefer depending on your URL parameters by doing
<?php
if ($_GET['success']) { ?>
<-- YOUR HTML SUCCESS CODE -->
<?php } else { ?>
<-- YOUR HTML FORM CODE -->
<?php }
?>
Ajax is the best solution for me (it can be difficult to understand but the code is clean), here an example of Ajax with your situation :
Extras is the ID of all the input in the form
Page is the PHP page to be executed (register-controller.php)
Origin is the ID where you want to put the result, Origin can be null.
(To have something in the return, you have to put an echo in the php file you specified in Page)
static Ajax(origin,Extras,page)
{
var xhr = new XMLHttpRequest();
let formData = new FormData();
for(var element in Extras)
{
if(document.getElementById(element))
{
formData.append(element,document.getElementById(element));
}
else
{
let checkbox = document.getElementsByName(element);
if(checkbox)
{
//Checkbox don't work with an ID so put instead a name
for(let i=0;i<checkbox.length;i++)
{
if(checkbox[i].checked)
{
formdata.append(element+i,"1")
}
else
{
formdata.append(element+i,"0")
}
}
}
}
}
xhr.open('POST',page);
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let i= xhr.responseText;
if(origin!=null)
{
if(document.getElementById(origin) && xhr.responseText!="")
// the result document.getElementById(origin).innerHTML=xhr.responseText;
}
finish(i);
}
else if (xhr.readyState === XMLHttpRequest.DONE && xhr.status != 200) {
// error message XHR,
let textError = "Ajax Error : " + xhr.status + ", " + xhr.statusText + ", ";
alert(textError);
}
});
// send
xhr.send(formData);
}
Im facing a problem Notice: Undefined index: company in C:\xampp\htdocs\new_exp\login.php on line 4
Errors
At here i have 3 database. exp, new_1 and new_2. In exp database have company table which contain id, company_name, and database_name attributes.
There are two database connection that i use which are dbconnection_main.php and dbconnection.php. dbconnection_main.php i used to call ada database which storing company_name and database_name table. Once user selected option of company_name when login in same time it will call the database_name.
The error occur when i login.
This is my index.php
<?php
session_start();
error_reporting(-1);
// Cek Active Link
function ActiveClass($requestUri)
{
$current_file_name = basename($_SERVER['REQUEST_URI'], ".php");
if ($current_file_name == $requestUri)
echo 'class="active"';
}
//check already login
if (!isset($_SESSION['UserId'])) {
header ('Location: login');
exit;
}
if ($_SESSION['level'] == 'APPROVAL'){
header ('Location: login');
exit;
}
//Link to page
if (isset($_GET['page']) && $_GET['page'] == 'ManageCategory') {
$page = "ManageExpenseCategory";
} else {
$page = 'dashboard';
}
//get global notification
include('includes/global.php');
//Get Header
include('includes/header.php');
//set global message notification
$msgBox ="";
if (file_exists('pages/'.$page.'.php')) {
// Load the Page
include('pages/'.$page.'.php');
} else {
// Else Display an Error
echo '
<div class="wrapper">
<h3>Err</h3>
<div class="alertMsg default">
<i class="icon-warning-sign"></i> The page "'.$page.'" could not be found.
</div>
</div>
';
}
include('includes/footer.php');
?>
So here is my login.php
<?php
session_start();
error_reporting(-1);
$_SESSION['db_company_name'] = $_POST['company'];
$msgBox = '';
//include notification page
include ('includes/notification.php');
//Include db Page
require_once ('includes/dbconnection.php');
//Include Function page
include ('includes/Functions.php');
//User Login
if(isset($_POST['login']))
{
$username = $mysqli->real_escape_string($_POST['email']);
$Password = encryptIt($_POST['password']);
if ($stmt = $mysqli->prepare("SELECT UserId, company_id, FirstName, LastName, Email, Password, level, admin_access, Currency from user WHERE Email = ? AND Password = ? "))
{
$stmt->bind_param("ss", $username, $Password);
$stmt->execute();
$stmt->bind_result($UserId_, $CompanyId_, $FirstName_, $LastName_, $Email_, $Password_, $Level_, $Admin_access_, $Currency_);
$stmt->store_result();
$stmt->fetch();
if ($num_of_rows = $stmt->num_rows >= 1)
{
session_start();
$_SESSION['UserId'] = $UserId_;
$_SESSION['FirstName'] = $FirstName_;
$_SESSION['LastName'] = $LastName_;
$_SESSION['level'] = $Level_;
$_SESSION['admin_access'] = $Admin_access_;
$_SESSION['Currency'] = $Currency_;
$_SESSION['company_id'] = $CompanyId_;
$compId = $_SESSION['company_id'];
$UserIds = $_SESSION['UserId'];
$company_q = mysqli_query($mysqli, "SELECT * FROM company_setting where company_id = '".$compId."'");
$company = mysqli_fetch_assoc($company_q);
$_SESSION['company_name'] = $company['company_name'];
if ($_SESSION['level'] === 'STAFF'){
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index">';
}
else
{
$msgBox = alertBox($LoginError);
}
}
}
}
?>
<!DOCTYPE html>
<html>
<div class="panel-body">
<?php if ($msgBox) {
echo $msgBox;
} ?>
<form class="form-horizontal m-t-20" method="post" action="" role="form">
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" onBlur="checkcompany(this.value)" type="email" required placeholder="<?php echo $Emails; ?>" name="email" id="email" autofocus>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" name="password" value="" required placeholder="<?php echo $Passwords; ?>">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<span id="result"><select name="company" id="company" class="form-control" required><option>company</option></select></span>
</div>
</div>
<div class="form-group text-center m-t-40">
<div class="col-xs-12">
<button type="submit" name="login" class="btn btn-primary btn-block text-uppercase waves-effect waves-light"><?php echo $SignIn; ?></button>
</div>
</div>
</form>
</div>
<script>
function checkcompany(v)
{
//alert(v);
var dataString = 'email='+v;
//document.getElementById('loginbtn').style.display = "none";
$.ajax({
type: "POST",
url: "checkaccount.php",
data: dataString,
cache: true,
success: function (result){
$("#result").html(result);
//document.getElementById('loginbtn').style.display = "block";
}
})
}
</script>
This is my checkaccount.php
<?php
error_reporting(-1);
session_start();
include("includes/dbconnection_main.php");
$email = $_POST['email'];
?>
<select name="company" id="company" class="form-control" required>
<option value="">----------------</option>
<?php
$company_q = mysqli_query($mysqli, "SELECT * FROM company");
while($company = mysqli_fetch_assoc($company_q))
{
//connect to sub database
$conn_hostname = "localhost";
$conn_database = $company['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqlii = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
$check_q = mysqli_query($mysqlii, "SELECT * FROM user WHERE Email = '".$email."' AND status = 'ACTIVE' AND password != ''");
$check = mysqli_num_rows($check_q);
if (!$check) {
printf("Error: %s\n", mysqli_error($mysqlii));
exit();
}
if($check >= 1)
{
?>
<option value="<?php echo $company['company_name']; ?>"><?php echo strtoupper($company['company_name']); ?></option>
<?php
}
mysqli_close($mysqlii);
}
?>
</select>
SO this is my dbconnection_main.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
?>
And This is my dbconnection.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
if(!isset($_SESSION))
{
session_start();
}
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}
$mysqlie = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
$get_database_q = mysqli_query($mysqlie, "SELECT * FROM company WHERE company_name = '".$company_name."'") or trigger_error(mysqli_error($mysqlie),E_USER_ERROR);
$get_database = mysqli_fetch_assoc($get_database_q);
if (!$get_database) {
printf("Errors: %s\n", mysqli_error($mysqlie));
exit();
}
$conn_hostname = "localhost";
$conn_database = $get_database['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqli = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
?>
I cannot detect the error since it only give me such general error prompt out. I think it might be related with dbconnection.php at this part which related with $_session..
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}
I have a problem.I need that the user can not send the form without having to write something
I have this form :
<div id="content" class="inner-wrapper reg">
<div id="mside">
<div class="section goback">
<div class="btn-back"><a class="back" onClick="history.go(-1)"><?= $lang['profile']['back'] ?></a></div>
</div>
<div class="section register">
<form id="mail-cons" method="post" action="" enctype="multipart/form-data" >
<div class="step2">
<ul class="step-ul">
<h2>Asesoría vía correo electrónico</h2>
<?//Primul pas pt user, descrierea problemei
if(loggedtype()=='user' AND $data['user_description']==''){?>
<div class="step-message sys-info"><img class='small icon' src='<?=$url_base?>css/images/icons/information.png' alt=''/> <?=$lang['mc']['user_step1']?></div>
<div class="row mail-cnsl">
</div>
<div class="row">
<textarea id="descriere2 " name="descriere" class="tinymce" rows="20" cols="50" style="width: 554px; height: 517px;"><?php echo $_REQUEST["descriere"];?></textarea>
</div>
<div class="row submit mail-cnsl">
<input type="submit" name="submitdesc" value="Enviar solicitud!" />
</div>
<? } ?>
And this function for validation:
<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if(window.clicked) return true;
if (validate_required(user_description_extra,"Por favor, introduzca el motivo del rechazo!")==false)
{user_description_extra.focus();return false;}
}
}
</script>
<script type="text/javascript">
function validate_length(f,a,l){
z=f.value;
x=z.length;
if (x<l){alert (a); f.focus(); return false;}
return true;
}
</script>
And this function for submit :
if(isset($_POST['submitdesc'])){
$upd = mysql_query("UPDATE discussion SET active='0' WHERE id='".$_GET['iddisc']."'") or die(mysql_error());
$sel = mysql_query("SELECT * FROM discussion WHERE id='".$_GET['iddisc']."'") or die(mysql_error());
$data = mysql_fetch_array($sel);
$upd_mc = mysql_query("UPDATE mail_counseling SET new_user=0, new_cons=1, user_description='".mysql_real_escape_string($_POST['descriere'])."' WHERE id_disc='".$_GET['iddisc']."'") or die(mysql_error());
//Notificari
if($_SESSION['loggedin']['type']=='user'){
$insid = $user['id_user'];
$type1 = 'user';
$type2 = 'client';
}else{
$insid = $cons['id_counselor'];
$type1 = 'consilier';
$type2 = 'counselor';
}
$insnotifs = mysql_query("INSERT INTO mc_notifs (type,id_user,message) VALUES ('".$_SESSION['loggedin']['type']."','".$insid."','".mysql_real_escape_string($message)."')") or die(mysql_error());
//End Notificari
//Send notification mail
$query_tpl_mail = "SELECT * FROM mails WHERE id_mails='6'";
$tpl_mail = mysql_query($query_tpl_mail, $conn) or die(mysql_error());
$row_tpl_mail = mysql_fetch_assoc($tpl_mail);
$subject = $row_tpl_mail['title_mail'.$lng_s_tb];
$message = $row_tpl_mail['description'.$lng_s_tb];
avertizare_mail($cons["email"],$subject,$lang['mc']['notif1']);
avertizare_mail($user["email"],$subject,$lang['mc']['notif11']);
header("Location: ".$url_base."$tip_user-account/mail-counseling/ok/");
exit;
}
But don't work .Can I help my?
Do not rely on the client side validation. Turning off javascript may leave your form vulnerable. You must do this work in php more securely and easily.
if(isset($_POST['submitdesc'])){
$desc = htmlspecialchars(trim($_POST['descriere'])));
if(isset($desc)){
$upd = mysql_query("UPDATE discussion SET active='0' WHERE id='".$_GET['iddisc']."'") or die(mysql_error());
$sel = mysql_query("SELECT * FROM discussion WHERE id='".$_GET['iddisc']."'") or die(mysql_error());
$data = mysql_fetch_array($sel);
$upd_mc = mysql_query("UPDATE mail_counseling SET new_user=0, new_cons=1, user_description='".mysql_real_escape_string($_POST['descriere'])."' WHERE id_disc='".$_GET['iddisc']."'") or die(mysql_error());
//Notificari
if($_SESSION['loggedin']['type']=='user'){
$insid = $user['id_user'];
$type1 = 'user';
$type2 = 'client';
}else{
$insid = $cons['id_counselor'];
$type1 = 'consilier';
$type2 = 'counselor';
}
$insnotifs = mysql_query("INSERT INTO mc_notifs (type,id_user,message) VALUES ('".$_SESSION['loggedin']['type']."','".$insid."','".mysql_real_escape_string($message)."')") or die(mysql_error());
//End Notificari
//Send notification mail
$query_tpl_mail = "SELECT * FROM mails WHERE id_mails='6'";
$tpl_mail = mysql_query($query_tpl_mail, $conn) or die(mysql_error());
$row_tpl_mail = mysql_fetch_assoc($tpl_mail);
$subject = $row_tpl_mail['title_mail'.$lng_s_tb];
$message = $row_tpl_mail['description'.$lng_s_tb];
avertizare_mail($cons["email"],$subject,$lang['mc']['notif1']);
avertizare_mail($user["email"],$subject,$lang['mc']['notif11']);
header("Location: ".$url_base."$tip_user-account/mail-counseling/ok/");
exit;
}else{
?><script>alert('Empty text field is not allowed.')</script><?php
}
}
Okay so i made a login button and this is the function code, But it keeps showing the error " Login unsuccessful, Please try again... "
Thank you in advance...
I didn't really get what you were asking for so i put almost all the code in cause i am trying and trying and can't figure it out...
<?php
include_once ("php_includesss121/check_login_statusopop.php");
// If user is already logged in, header that user away
if ($user_ok == true)
{
header("location: user.php?u=" . $_SESSION["username"]);
exit();
}
?><?php
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if (isset($_POST["e"]))
{
// CONNECT TO THE DATABASE
include_once ("php_includesss121/db_conxx12.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = md5($_POST['p']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// FORM DATA ERROR HANDLING
if ($e == "" || $p == "")
{
echo "login_failed";
exit();
}
else
{
// END FORM DATA ERROR HANDLING
$sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if ($p != $db_pass_str)
{
echo "login_failed";
exit();
}
else
{
// CREATE THEIR SESSIONS AND COOKIES
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime('+30 days') , "/", "", "", TRUE);
setcookie("user", $db_username, strtotime('+30 days') , "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime('+30 days') , "/", "", "", TRUE);
// UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
}
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Log In</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<script src="js/mainopop.js"></script>
<script src="js/ajaxopop.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function login(){
var e = _("email").value;
var p = _("password").value;
if(e == "" || p == ""){
_("status").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("status").innerHTML = 'Please wait...';
var ajax = ajaxObj("POST", "login.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
_("status").innerHTML = "Login unsuccessful, Please try again...";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("e="+e+"&p="+p);
}
}
</script>
</head>
<body>
<?php
include_once ("template_pageTopLoginPageopop.php"); ?>
<div id="pageMiddle">
<h2>Welcome ...</h2>
<h3>Log In Here</h3>
<!-- LOGIN FORM -->
<form id="loginform" onsubmit="return false;">
<div>Email Address:</div>
<input type="text" id="email" onfocus="emptyElement('status')" maxlength="300">
<div>Password:</div>
<input type="password" id="password" onfocus="emptyElement('status')" maxlength="100">
<br />
<br />
<button id="loginbtn" onclick="login()">Log In</button>
<p id="status"></p>
Forgot Your Password?
</form>
<!-- LOGIN FORM -->
</div>
<?php
include_once ("template_pageBottomopop.php");
?>
</body>
</html>
And Javascript file ajaxopop.js:
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if (x.readyState == 4 && x.status == 200) {
return true;
}
}
Please note that password in DB Table should be md5
encrypted as in PHP, you are encrypting it to match further. If not, just remove md5 encryption from PHP Code.
I have an update password page that won't let me enter the actual current password for the current password field. Instead, it wants the hashed password. Once changed however, the new one is then hashed, which is a good thing. I just need to be able to enter the actual password and not hashed.
Yes I know, no md5; this is more for testing is all.
changepassword.js
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}
</script>
updatepassword.php
<?php
include 'core/login.php'; === this contains the connection, it's obviously good ===
include 'includes/head.php'; === changepassword.js is linked in the head ===
if(count($_POST)>0) {
$result = mysqli_query($link, "SELECT *from users WHERE id='" . $_SESSION["id"] . "'");
$row = mysqli_fetch_array($result);
if($_POST["currentPassword"] == $row["password"]) {
mysqli_query($link, "UPDATE users set `password`='" .md5(md5($_POST['newPassword'])) . "' WHERE id='" . $_SESSION["id"] . "'");
$message = "Password Changed";
} else $errormessage = "Current Password is not correct";
}
print_r($_SESSION);
?>
form on same page:
<div class="container">
<div class="text-center">
<h4>Change password below</h4>
</div><br />
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<div class="message"><?php if(isset($errormessage)) { echo $errormessage; } ?></div>
<div class="col-md-4 col-md-offset-4">
<form name="frmChange" method="post" action="" onSubmit="return validatePassword()">
<div class="form-group">
<label>Current Password*</label>
<input type="text" name="currentPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>New Password*</label>
<input type="text" name="newPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>Confirm Password*</label>
<input type="text" name="confirmPassword" class="form-control input-md" />
</div>
<br />
<div class="text-center">
<input type="submit" name="submit" class="btn btn-success" value="Submit" />
</div>
</form>
</div>
</div>
Your problem is here:
if($_POST["currentPassword"] == $row["password"]) {
You are comparing the actual text version of the hash (say "password") to the hashed version of that password (say "213y789hwuhui1dh"). This evaluates out to:
if("password" == "213y789hwuhui1dh") {
Which obviously is never accurate. All you have to do to solve the problem is hash the password in the same way you did when you created it. If I understand your code properly, that should be:
if(md5(md5($_POST["currentPassword"]))==$row["password"]) {
SIDE NOTE ON SQL INJECTION
Please note that this code would be super easy to inject into. All a user would have to do is end the "currentPassword" POST value with '; SHOW DATABASE; and they would have unlimited access to your server's MySQL database. Consider learning to use MySQLi Prepared Statements. They are easy to understand, and easy to implement.
I went overboard. Your other question was closed. Juuuuust gonna leave this here... I'm using PHP version PHP 5.2.0.
http://php.net/manual/en/faq.passwords.php
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
<?php
// so I don't actually have to test form submission, too...
$_POST['current_password'] = 'Tacotaco';
$_POST['new_password'] = 'NINrocksOMG';
$_POST['confirmPassword'] = 'NINrocksOMG';
$_SESSION['id'] = 1;
// this is Tacotaco encrypted... update your db to test
// update users set password = '$2y$10$fc48JbA0dQ5dBB8MmXjVqumph1bRB/4zBzKIFOVic9/tqoN7Ui59e' where id=1
// the following is sooooo ugly... don't leave it this way
if (!isset($_SESSION['id']) or empty($_SESSION['id']) or
!isset($_POST['current_password']) or empty($_POST['current_password']) or
!isset($_POST['new_password']) or empty($_POST['new_password']) or
!isset($_POST['confirmPassword']) or empty($_POST['confirmPassword']) ) {
$message = 'Please enter your password';
}
else {
$sid = $_SESSION['id'];
$currpass = $_POST['current_password'];
$newpass = $_POST['new_password'];
$conpass = $_POST['confirmPassword'];
$message = validate_password($sid, $currpass, $newpass, $conpass);
}
print "<br/>$message<br/>";
function validate_password($sid, $currpass, $newpass, $conpass) {
$mysqli = mysqli_connect('localhost','root','','test')
or die('Error ' . mysqli_error($link));
$stmt = $mysqli->prepare('select id, password from users where id = ?');
$stmt->bind_param("s", $sid);
$stmt->execute();
$stmt->bind_result($userid, $userpass);
$message = '';
if ($stmt->fetch()) {
$stmt->close();
if (strlen($newpass) < 8) {
$message = 'Please enter a password with at least 8 characters';
}
elseif (!preg_match('`[A-Z]`', $newpass)) {
$message = 'Please enter at least 1 capital letter';
}
elseif ($newpass !== $conpass) {
$message = 'Your passwords do not match.';
}
else {
if (password_verify($currpass, $userpass)) {
$hashed_new = password_hash($newpass, PASSWORD_BCRYPT);
$query = 'update users set password = ? where id = ?';
$stmt_new = $mysqli->prepare($query);
$stmt_new->bind_param('ss', $hashed_new, $sid);
if ($stmt_new->execute()) {
$message = 'Password Changed';
}
else {
$message = $mysqli->error;
}
}
else $message = 'Current Password is not correct';
}
}
else {
$message = 'user not found for id $sid';
}
$mysqli->close();
return $message;
}
?>