This is the code where this used to verify the token by getting it from url and matching it with databse. and when matches it updates a db field and gives a alert that account is verified according to code. It works good. but when url token is wrong and it doesnt updates databse field but still gives same alert that account is verified. but it should use that else fumction. But still it uses that if function. What is the reason behind this error?
session_start();
include 'partials/_dbconnect.php';
if(isset($_GET['token'])){
$token = $_GET['token'];
$updatequery ="UPDATE `users` SET `status` = 'active' WHERE `users`.`token` = '$token' " ;
$query = mysqli_query($conn, $updatequery);
if($query){
echo '<script>alert("Your account is verified successfully. Please login now. !")</script>';
echo '<script> window.location.href = "/login.php"</script>';
}
else{
echo '<script>alert("This link is not valid. Acoount verification failed !")</script>';
echo '<script> window.location.href = "/index.php"</script>';
}
}
?>``
`
$query will return as true as long as the query executed successfully. You aren't matching the token at all. You're updating it. If the token doesn't match, the database doesn't update, but the query itself still returns true, that 0 rows were updated.
What you need to do is check if the token exists in the database first. If it does exist, then update it. Something like this:
if(isset($_GET['token'])){
$token = $_GET['token'];
$checkquery ="SELECT `token` FROM `users` WHERE `users`.`token` = '$token' " ;
$result = mysqli_query($conn, $checkquery);
if(mysqli_num_rows($result) >0){
$updatequery ="UPDATE `users` SET `status` = 'active' WHERE `users`.`token` = '$token' " ;
$query = mysqli_query($conn, $updatequery);
echo '<script>alert("Your account is verified successfully. Please login now. !")</script>';
echo '<script> window.location.href = "/login.php"</script>';
}
else{
echo '<script>alert("This link is not valid. Acoount verification failed !")</script>';
echo '<script> window.location.href = "/index.php"</script>';
}
}
Related
I'm trying to make a registration form for my website. I'm using the code below. All the error handlers work fine since it's adding the users into my database. I've trid to add ob_start. I removed all white spaces using a plugin for sublime text. I tried to use javascript instead of php (top.window). I also tried to use full url instead of just directories. But when I click submit it doesnt redirect me to the address I put after Location. When I click the button it takes me to this php file but doesnt redirect me back to the registration page which is a seperate file(I know there are a lot of similar questions that have been asked but they dont seem to work for my situation).
Does anyone know how to fix that?
if (isset($_POST['submit'])){
include_once 'db.php';
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
//error handlers
//Check for empty fields
if (empty($uid) || empty($pwd) || empty($email)) {
header("Location : /login/register.php?signup=empty");
exit();
} else{
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $uid)) {
header('Location: /login/register.php?signup=invalid');
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header('Location : /login/register.php?signup=email');
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header('Location : /login/register.php?signup=usertaken');
exit();
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the databse
$sql = "INSERT INTO users (user_uid, user_pwd, user_email) VALUES ('$uid', '$hashedPwd', '$email');";
mysqli_query($conn, $sql);
header('Location : /login/register.php?signup=success');
exit();
}
}
}
}
} else {
header('Location : /login/register.php');
exit();
}
Solved - Removing space after "location" answer by Nigel Ren
Make sure you don't have a space after location and before the :...
header('Location : /login/register.php');
should be
header('Location: /login/register.php');
Try to use absolute URI
$host = $_SERVER['HTTP_HOST'];
header("Location: ".$host."/login/register.php?signup=empty");
replace all header to location.assign
header('Location : /login/register.php');
replace to
echo "<script>location.assign('/login/register.php')</script>";
after use location assign , maybe problem sol..
I am trying to use jQuery, AJAX, PHP, and MySQL to check if an email entered into a form already exists in a database.
This is my current jQuery code :
$.post('check-email.php', {'suEmail' : $suEmail}, function(data) {
if(data=='exists') {
validForm = false;
$suRememberMeCheckbox.css('top', '70px');
$suRememberMeText.css('top', '68px');
$signUpSubmit.css('top', '102px');
$tosppText.css('top', '115px');
$suBox.css('height', '405px');
$suBox.css('top', '36%');
$errorText.text('The email has been taken.');
return false;
};
});
And this is my PHP code:
<?php include("dbconnect.php") ?>
<?php
$sql = "SELECT email FROM users WHERE email = " .$_POST['suEmail'];
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($row) > 0) {
echo "exists";
}
?>
When I go through with the sign up form, when I use an email already in the database, the error text never changes to what I specified, but instead to some other error cases I have coded. Why is this not working! Thanks so much!
Use This Code: Working Perfectly:
<?php
include("dbconnect.php");
$sql = "SELECT email FROM users WHERE email = '" .$_POST['suEmail']."' ";
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($select) > 0) {
echo "exists";
}
?>
If its not changing that means you might have a error with your query. Check developer options on your browser under network. There you can see all ajax calls being made. Click on look at the response. Check to see if there was an error with your query.
Also you have to validate the form submission.
Something like.
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
//maybe send a token over with the form to prevent form spoofing
if($_POST['token'] === $_SESSION['token'])
{
// all your code goes in here
// you provably want to check that is a real email also
// check email input against regular expression
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//if valid email to variable and escape data
$e = sanitizeString($_POST['email']);
}else
{
/// if not a real email to errors array
$reg_errors['email'] = 'Please enter a valid email address!';
}
}
}
You have to use prepare statements in your queries.
I found and fixed a little bit I am not so good with PHP but any improvements are welcome.
The problem is that sometimes in Chrome and Opera but only sometimes after login sucess the script redirect to a welcome page with javascript redirection after 5 secs. But sometimes it just get stuck and does not redirect but just show a white page without error and other times it redirect and worls fine. What can it be?
Here is the code
<?php session_start();?>
<?php
include 'inc/connection.php';
$db=mysqli_connect($dbserver, $dbuser, $dbpass, $dbname)or die("DB connection error...");
$username_to_sanitize = $_POST['username'];
$password_to_sanitize = $_POST['password'];
$sanitized_username = mysqli_real_escape_string($db, $username_to_sanitize);
$sanitized_password = mysqli_real_escape_string($db, $password_to_sanitize);
$query = "SELECT password, salt, privilege, username FROM members WHERE username = '$sanitize_username'";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 0) // User not found. Redirected to login page.
{header('Location:login.php?message=Username not found, please try again');}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $sanitized_password) );
if($hash != $userData['password']) // Incorrect passw. Redirected to login page.
{header('Location:error.php?message=Wrong password, please try again');}
else if($userData['privilege']=="ADMIN"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=admins/index.php');}
else if($userData['privilege']=="MODERATOR"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=moderators/index.php');}
else if($userData['privilege']=="MEMBER"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=members/index.php');}
else if($userData['privilegio']=="BANNED"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=banned/index.php');}
else{
header('Location:error.php?message=su need privileges to acces this site');
exit();
}
?>
After reading and testing new scripts found on internet I still cannot fix this problem after 2 months. Any idea?
You have a lot of duplication in your code, which is bad because each place that you duplicate means that you need to change it when you update the code, which means that there are more places for bugs to pop up later.
To help, I placed in only one session_start(), and I converted the if/elseif/elseif/elseif... to a switch statement.
Instead of dealing with the location headers themselves, I've replaced those with the http_redirect function, which basically does it for you. To boot, it encodes the URLs for you so you don't have to worry about that.
If you keep seeing a blank page, then you should check the webserver's logs (apache or nginx or php-fpm, or whatever) to see if the errors are there. Otherwise, turn on better error reporting; quite often blank pages are just errors that haven't been reported.
<?php
session_start();
include 'inc/connection.php';
$db = mysqli_connect($dbserver, $dbuser, $dbpass, $dbname) or die('DB connection error...');
$sanitized_username = mysqli_real_escape_string($db, $_POST['username']);
$sanitized_password = mysqli_real_escape_string($db, $_POST['password']);
$query = "SELECT password, salt, privilege, username FROM members WHERE username = '$sanitized_username'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) == 0) {
// User not found. Redirected to login page.
http_redirect('login.php', array('message' => 'Username not found, please try again'), true);
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $sanitized_password) );
if($hash != $userData['password']) {
// Incorrect passw. Redirected to login page.
http_redirect('error.php', array('message' => 'Wrong password, please try again'), true);
}
// Just set the username once
$_SESSION['username'] = $userData['username'];
switch ( $userData['privilege'] ) :
case 'ADMIN':
http_redirect('redirection.php', array('URL' => 'admins/index.php'), true);
break;
case 'MODERATOR' :
http_redirect('redirection.php', array('URL' => 'moderators/index.php'), true);
break;
case 'MEMBER' :
http_redirect('redirection.php', array('URL' => 'members/index.php'), true);
break;
case 'BANNED' :
http_redirect('redirection.php', array('URL' => 'banned/index.php'), true);
break;
default:
// The message is weird. Should it be:
// 'You need privileges to access this site' or something like that?
http_redirect('error.php', array('message' => 'su need privileges to acces this site'), true);
break;
endswitch;
http_redirect('error.php', array('message' => 'su need privileges to acces this site'), true);
?>
<?php
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
if ($_GET['type'] == "upload")
{
$title=$_GET['title'];
$creator=$_GET['creator'];
$ingredient=$_GET['ingredient'];
$serving=$_GET['serving'];
$note=$_GET['note'];
$prepare=$_GET['prepare'];
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUE ('$title','$creator','$ingredient','$serving','$note','$prepare')";
if(mysql_query($insertsql,$db))
{echo 1; }
else
{echo 0; }
}
?>
<script>
$.ajax({
type : "get",
url : "dataconn.php",
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredien t+"&serving="+serving+"¬e="+note,
success : function(data){
alert(data);
}
});
</script>
</head>
</html>
When I pass variable in to PHP from JavaScript it able to save in database but I need some value like the data have been successful save and will come out a alert 1 or 0.
But once I connect to database it cant alert any more. Like some error blocking in database but still can save just does not come out any alert. If I remove it then it running all
It does not sure alert as well.
Change this line:
if(mysql_query($insertsql,$db))
To this line; using mysqli_* extensions and correctly using $con for the query instead of $db which is a connection variable you don’t have set anywhere:
if(mysqli_query($con,$insertsql))
Also, you should set your MySQL calls to return errors like this:
$con=mysqli_connect("localhost","root","","recipe") or die(mysqli_connect_errno());
And change this as well:
$result = mysqli_query($con,$insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
Also you are using VALUE in the query when it should be VALUES:
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUES ('$title','$creator','$ingredient','$serving','$note','$prepare')";
Not to mention in your JavaScript AJAX code you have +ingredien t+ when it should be +ingredien t+:
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredient+"&serving="+serving+"¬e="+note,
At the top why are you setting variables for the MySQL connection but then putting values inline?
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
And finally, I did a cleanup of your main MySQL logic code. I have included mysqli_stmt_bind_param, mysqli_free_result & mysqli_close and set a foreach loop for $_GET values. This simply should work:
// Credentials.
$host="localhost";
$user="root";
$password="";
// Connecting, selecting database
$con = mysqli_connect($host, $user, $password, 'recipe') or die(mysqli_connect_errno());
if (isset($_GET['type']) && !empty($_GET['type']) && $_GET['type'] == "upload") {
// Set a '$_GET' array and roll through each value.
$get_array = array('title', 'creator', 'ingredient', 'serving', 'note', 'prepare');
foreach ($get_array as $get_key => $get_value) {
$$get_value = isset($_GET[$get_value]) && !empty($_GET[$get_value]) ? $_GET[$get_value] : null;
}
// Set the query.
$insertsql = "INSERT INTO `upload` (`title`, `creator`, `ingredient`, `serving`, `note`, `prepare`)"
. " VALUES (?, ?, ?, ?, ?, ?)"
;
// Bind the params.
mysqli_stmt_bind_param($insertsql, 'ssssss', $title, $creator, $ingredient, $serving, $note, $prepare);
// Run the query.
$result = mysqli_query($con, $insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
}
I'll make this as short and sweet as possible.
I have this script called usernameget.php which echos the currently logged in username:
<?php
include 'functions.php';
include 'db_connect.php';
sec_session_start();
$userId = $_SESSION['user_id'];
if(login_check($mysqli) == true) {
$con=mysqli_connect("localhost","myusername","mypass","mysqldb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT members.username FROM members WHERE id= $userId");
while ($row = mysqli_fetch_assoc($result))
{
echo $row['username'];
}
/* free result set */
mysqli_free_result($result);
mysqli_close($con);
} else {
echo 'Null User <br/>';
}
?>
This script uses functions.php (part of a secure login script located here: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL#Create_PHP_Functions ) in order to function. sec_session_start(); is just a custom session_start, but functions.php also makes it possible to get the username via $user_id.
The problem is, when I include usernameget.php in the main page (which also uses functions.php to secure,) it throws errors because it's trying to redeclare sec_session_start();
I can strip usernameget.php of this security but obviously since it banks on functions.php / sec_session_start(); it doesn't work afterwards. I've tried to write a specific USERNAMEGETfunctions.php without the session stuff for usernameget.php to use but I'm not adept enough to get it working, and it feels like an inelegant solution.
So as I understand it: functions.php and sec_session_start(); are used to secure the main page so the includes on the main page can't use functions.php or it will conflict. Would anyone be able to show me how to get this script going without redeclaring/conflicting?
Included below is the entire functions.php
<?php
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(); // regenerated the session, delete the old one.
}
function login($email, $password, $mysqli) {
// Using prepared Statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
$stmt->fetch();
$password = hash('sha512', $password.$salt); // hash the password with the unique salt.
if($stmt->num_rows == 1) { // If the user exists
// We check if the account is locked from too many login attempts
if(checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
if($db_password == $password) { // Check if the password in the database matches the password the user submitted.
// Password is correct!
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
$user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); // XSS protection as we might print this value
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts (user_id, time) VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
function checkbrute($user_id, $mysqli) {
// Get timestamp of current time
$now = time();
// All login attempts are counted from the past 2 hours.
$valid_attempts = $now - (2 * 60 * 60);
if ($stmt = $mysqli->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time > '$valid_attempts'")) {
$stmt->bind_param('i', $user_id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// If there has been more than 5 failed logins
if($stmt->num_rows > 5) {
return true;
} else {
return false;
}
}
}
function login_check($mysqli) {
// Check if all session variables are set
if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
if ($stmt = $mysqli->prepare("SELECT password FROM members WHERE id = ? LIMIT 1")) {
$stmt->bind_param('i', $user_id); // Bind "$user_id" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if($stmt->num_rows == 1) { // If the user exists
$stmt->bind_result($password); // get variables from result.
$stmt->fetch();
$login_check = hash('sha512', $password.$user_browser);
if($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
}
?>
Don't use plain include for core function libraries, the kind which tend to get included in ALL your scripts. Use include_once instead, so that PHP will only ever include the file once, and then ignore any further include attempts. This will prevent your function redeclaration errors.
You must use require_once instead include_once because your program not will run without that files...
include_once produce warning when try to include the file and it fails.
require_once produce fatal error when try to include the and it fails.
For core libs, you should use require_once. (http://www.php.net/manual/pt_BR/function.require.php)
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.