So I'm trying to check if the email is already in use (for a password reset). So I have my JS
//Check if email exists
$(document).ready(function() {
//listens for typing on the desired field
$("#email").keyup(function() {
//gets the value of the field
var email = $("#email").val();
//here is where you send the desired data to the PHP file using ajax
$.post("../classes/check.php", {email:email},
function(result) {
if(result == 1) {
//Email available
console.log("Good");
}
else {
//the email is not available
console.log("Bad");
}
});
});
});
And then my PHP
<?php
//Include DB
include_once '../db.php';
if(isset($_POST['email'])){
//Get data
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
}
else{
header('Location: /');
}
//Send requst to DB
$stmt = $con->prepare("SELECT * FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount() > 0){
//Email found
echo 1;
}
else{
//Email not found
echo 0;
}
So I start off by making sure there's a recording in my DB. Which there is, so I enter it. Now I go over to the console and all I get is Bad, which means that the email is not found, but it's in the database. So I'd assume all it returns is 0. Any ideas? Could it be an error in my code?
The PDO documentation warns that rowCount might not work with all drivers. A more reliable and efficient way to do it is:
$stmt = $con->prepare("SELECT COUNT(*) as count FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['count'] > 0) {
echo 1;
} else {
echo 0;
}
Another thing to try:
$email = trim($_POST['email']);
because sometimes there's extra whitespace in theinput field.
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to let a user log in. If the password and username is wrong, I want a popup to appear alerting the user on the error. When they close the alert, it goes back to index.php which is back to login screen.
But when it is wrong password/username, ends up going back to index.php without any popup messages first. My browser setting is not blocking any popups. Can I know what I'm doing wrong please.
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">alert("Please enter valid username and password");</script>';
header("location:index.php");
}
?>
//login.php
<?php
$username = "exampleuser";
$password = "examplepass";
$host = "localhost";
$dbHandle = mysql_connect($host, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("database_name", $dbHandle);
$myUserName = $_POST['user'];
$myPassword = $_POST['pass'];
if(ctype_alnum($myUserName) && ctype_alnum($myPassword)){
$query1 = "SELECT * FROM users WHERE username='$myUserName'";
$result1 = mysql_query($query1);
$count1 = mysql_num_rows($result1);
if($count1 == 1){
$query2 = "SELECT password FROM users WHERE username='$myUserName'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if(password_verify($myPassword, $pass)){
$seconds = 120 + time();
setcookie(loggedIn, date("F js - g:i a"), $seconds);
header("location:mysite.php");
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
?>
If you send headers to php it goes directly on index.php after the page goes in your condition.
If you try this code:
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
you will see that your code is correct. You need to track an event on popup closing to redirect to index.php via ajax or via http redirect.
EDIT 1:
Here you have a complete page with pdo. This is not the best way to do the job but it works. As you will see in the comments you have to avoid xss attacks and you should change database structure saving password hashed and salt to hide the users' clear password.
Here's the code.
<?php
//login.php
//connection via PDO
try{
$pdo = new PDO ('mysql:host=localhost; dbname=database_name', 'exampleuser' , 'examplepass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//alert errors and warnings
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
exit('Database Error.');
}
//prepared statements sanitize input binding parameters, for you but you can use some libraries to prevent sql injection
$myUserName = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));;
$myPassword = trim(filter_var($_POST['pass'], FILTER_SANITIZE_STRING));;
if(!empty($myUserName) && ctype_alnum($myUserName) && !empty($myPassword) && ctype_alnum($myPassword)){
$query1 = $pdo->prepare("SELECT password FROM users WHERE username = :username_param");
//bind parameter avoiding principal injection (pdo does not cover xss attacks, avoid it with other methods)
$query1->bindParam("username_param", $myUserName);
$result = $query1->fetch();
// or you can do $result = $query1->fetchColumn(); to get directly string instead of array
if($result['password']){
//you should use password_verify() if you have an hash stored in database, you should not save password in database.
//please google about best practice storing password, it's full of beautiful guides
//bad practice but will do the work
if($myPassword == $result){
$seconds = 120 + time();
setcookie('loggedIn', date("F js - g:i a"), $seconds);
header("location:mysite.php");
}else{
printAlert("Password incorrect");
}
}else{
printAlert("Username not valid");
}
}
else{
printAlert("Invalid data");
}
function printAlert($text){
echo "<script language='javascript'>
alert('$text');
window.location.href = 'http://index.php';
</script>";
die();
}
?>
I am trying to pass user's info from mysql to the webpage, if the user has logged in but can't get it to work. If I put a wrong email or password it will show the error message but if the credentials are ok it would do anything...
on php file:
$sql = "SELECT * FROM users WHERE email='$l_email' AND password='$l_password'";
$query = mysql_query($sql) or die ('Error: ' . mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1)
{
echo "You have entered a wrong email or password!";
}
else {
$memberInfo = array();
while( $row = mysql_fetch_array( $query ) )
{
$memberInfo[] = $row;
}
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
}
on js file:
$.post("./includes/checkOut.php",{ l_email1: l_email, l_password1: l_password },
function(data) {
if(data=='1')
$("#checkOut_form")[0].reset();
$("#login_returnmessage").html("");
$("#memberInfo").hide("");
var memberInfo = jQuery.parseJSON(memberInfo);
for( var i in memberInfo )
{
var f_name = memberInfo[i].f_name;
var l_name = memberInfo[i].l_name;
var phone = memberInfo[i].phone;
}
$("#loggedinInfo").show("");
$('#_f_name').val(f_name);
$('#_l_name').val(l_name);
$('#_email').val(l_email);
$('#_phone').val(phone);
}
$("#login_returnmessage").html(data);
});
If you use return outside a function then it terminates the script at that point. This is exactly what you're doing here:
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
You need to remove the return statement.
You should also add a Content-type: header to the response to tell the browser to expect JSON:
header('Content-type:application/json');
echo json_encode( $memberInfo );
Your Javascript code is checking the response for the value 1, which you're not sending, so the code that updates the display won't execute.
Lastly:
don't store passwords unencrypted - use password_hash()
don't use mysql as it's deprecated - use mysqli or PDO
ensure you escape your inputs before passing them to the database (or better, use prepared statements (not supported by mysql_*()).
i have a page login
in page have html form with textboxes and submit button
and in top of page i have PHP code thet chacke if name and password in database
if name and password in database page go to new page and pass the name and password to next page
i can do it with get metod like the vars in the URL
but i want to pass and go to new page with Post metod
how i can do it??
pleas help me with code....
in code html :
form name="frmlogin"action="<?= $_SERVER['PHP_SELF'] ?>" method="post" >
and in top of the page have PHP code:
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
/*header('Location: YOUR_LOCATION');
exit;*/
$msg = "Username and password match";
echo '<script type="text/javascript">
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
help me to change the javascript window.location to post metod
You can go for php redirect also.
header('location:smartphon100.php?name='. $name .'&password='. $password) ;
BTW: you are passing password in browser?
If I understand correctly, you're trying to redirect a user after successfully logging in.
I see that your current code attempts to redirect using Javascript, the issue seems to be with the quotes on the value you tried to enter.
Try to change this line:
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
to this:
window.location.href = "smartphon100.php?name='.$name.'&password='. $password";
Overall you should read about security as the code you presented is very vulnerable.
PHP: SQL Injection - Manual
If you're trying to pass the values to another page in a POST method using Javascript, you could take a look at this answer:
JavaScript post request like a form submit
Although as I don't see a reason for posting the values more than once,
I recommend you to read about PHP sessions, cookies, and encryption, which allow you to store values that you can use across the website securely.
A simple example to using session:
<?php
//Starts the session, you need to use this line in every PHP file that'll need to access session variables
session_start();
$_SESSION['user'] = "Donny"; //Storing a user name
?>
A simple example of session use with your code:
Foo.php
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['user'] = $name;
$_SESSION['pass'] = $password;
$msg = "Username and password match";
echo '<script type="text/javascript">window.location.href = "smartphon100.php";</script>';
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
Bar.php
<?php
session_start();
//Accessing the values:
echo $_SESSION['user'];
echo $_SESSION['pass'];
?>
NOTE:
It's not good to store values like that as again, they're not secure, please read about hashing passwords.
PHP: Password Hashing
I'm looking to get other information when logging into my database. I'm looking to get the TechID of the tech that has successfully signed in and store it within "output" in the second section. Wondering if you could help.
PHP:
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT TechNo, TechName, TechUser,TechPass FROM $tbl_name
WHERE TechUser='$myusername' and TechPass='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
echo "***TechID goes here";
}
else
{
echo 'false';
}
Post Method:
function checkEvents()
{
var username = $("#username").val();
var password = $("#pass").val();
$.post('checklogin.php', {username: username, password: password},
function(output){
if(output == 'false')
{
Win('#geteventslogin', 0);
popupcetion('#loginfailed', 1);
}
else
{
Win('#geteventslogin', 0);
alert(output); ///output = TechID number.
popupcetion('#getevents', 1);
}
});
}
What im trying to do is display a list of jobs from another database, each tech is assigned jobs and i want only to display the correct jobs for that tech. This question has probably been asked before. If you could point me towards a post or answer my question, i would be much appreciative.
Thanks in advance.
I think your code should look like this
$sql="SELECT TechID FROM $tbl_name
WHERE TechUser='".$myusername."' and TechPass='".$mypassword."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
$row = mysql_fetch_assoc($result);
echo $row['TechID'];
}
else
{
echo 'false';
}
Hope it will help.
I think you should take more care about stripslashes and echoing variables:
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$myusername = get_magic_quotes_gpc() ? stripslashes($myusername) : $myusername;
$mypassword = get_magic_quotes_gpc() ? stripslashes($mypassword) : $myusername;
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT TechNo, TechName, TechUser,TechPass FROM $tbl_name
WHERE TechUser='$myusername' and TechPass='$mypassword'";
$result=mysql_query($sql);
if( mysql_num_rows($result) )
{
$fields = mysql_fetch_assoc($result);
echo "TechID = ". htmlspecialchars($fields['TechNo']); // or 'TechID' !?
}
else
{
echo 'false';
}
;)
I am trying to create a signup form that checks if the user exists in the database, I inserted a sample user and when I tried signing up with that user it didn't say its already been taken. What have I done wrong?
The JavaScript:
function formSubmit()
{
document.getElementById('email_valid').innerHTML = '';
var temail=document.forms["signup_form"]["temail"].value.replace(/^\s+|\s+$/g, '');
var atpos=temail.indexOf("#");
var dotpos=temail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=temail.length)
{
//alert("Not a valid e-mail address");
setTimeout(function(){document.getElementById('email_valid').innerHTML = '<br/>Email must be valid...';},1000);
var temailsub=0;
}
else
{
$.post('/resources/forms/signup/email.php',{email: temail}, function(data){
document.getElementById('email_valid').innetHTML = data;
if(data.exists){
document.getElementById('email_valid').innetHTML = '<br/>The email address you entered is already in use.';
var temailsub=0;
}else{
var temailsub=1;
}
}, 'JSON');
}
if(temailsub==1e)
{
setTimeout(function(){document.getElementById("signup_form").submit();},1000);
}
else
{
return false;
}
}
The PHP file (email.php):
<?php
header('content-type: text/json');
require_once $_SERVER['DOCUMENT_ROOT']."/resources/settings.php";
$query = $pdo->prepare("SELECT * FROM users WHERE email=:email");
$query->execute(array(
":email"=> $_POST['email']
));
echo json_encode(array('exists' => $query->rowCount() > 0));
?>
I have checked and double checked the code, I still cannot see why its not detecting that the email has already been used... what do i need to do to fix this and avoid this in the future?
The problem is that PDOStatement::rowCount() returns the number of rows affected by the last SQL statement. You are performing a SELECT so this value will always be 0. SELECT does not affect any rows. Instead you need to count the number of rows:
$query = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email=:email");
$query->execute(array(
":email"=> $_POST['email']
));
$rows = $query->fetchColumn();
echo json_encode(array('exists' => $rows);
Also from jtheman's comment above, you should replace innetHTML with innerHTML in your JavaScript.