instead using die in error - javascript

i'm currently making a registration page. It includes hashing of password and validation. When I use "die" it stops the form and displays the error. I want to display the error on the same page.
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
$ErrorTest ="";
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['username']))
{
$ErrorTest = "Please enter a username.";
}
if(empty($_POST['password']))
{
$ErrorTest = "Please enter a password.";
}
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$ErrorTest = "Invalid E-Mail Address";
}
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$ErrorTest = "Failed to run query: " . $ex->getMessage();
}
$row = $stmt->fetch();
if($row)
{
$ErrorTest = "This email address is already registered";
}
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$ErrorTest ="Failed to run query: " . $ex->getMessage();
}
$row = $stmt->fetch();
if($row)
{
$ErrorTest = "This username is already in use";
}
$query = "
INSERT INTO users (
username,
password,
salt,
email
) VALUES (
:username,
:password,
:salt,
:email
)
";
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
{
$password = hash('sha256', $password . $salt);
}
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$ErrorTest = "Failed to run query: " . $ex->getMessage();
}
// This redirects the user back to the login page after they register
header("Location: myprofile.php");
$ErrorTest = "Redirecting to admin_login.php";
}
?>
the die ("please enter a username") I want to display it on the same page. I tried also to put it on a javascript but when I put wrong infomation on one textboxes, it pop-ups all the error and displays the query.

The way I'd go about it is replacing die with a variable assignment to $error
i.e.
die("Failed to run query: " . $ex->getMessage());
replace with
$error = ("Failed to run query: " . $ex->getMessage());
and then wrap your registration logic with conditional statements checking if is set or if empty (up to you)
On your form you can then output this message using echo.
Edit
As you're redirecting to another page and not processing on the same page then adjust your code to
if($ErrorTest != ''){
header("Location: register.php?error=".$ErrorTest);
}
else{
header("Location: myprofile.php");
}
On the register.php page just check for the $_GET['error'] and then output it.
You're also always registering the user even if it errors so may be worth adding this code into the 'else'

Related

How to stop alert box to display when back button is pressed in PHP?

My PHP code works properly but the problem is, when I press the back button, the alert dialog again shows up. The alert dialog is needed while logging in, and it works properly. But when I press the back button, it again shows the alert box.
<?php
if($_POST){
$host = "localhost";
$user = "root";
$pass = "";
$db = "erp";
$userId = $_POST['myusername'];
$password = $_POST['mypassword'];
$conn = mysqli_connect($host,$user,$pass,$db);
$query = "SELECT * from user where user_id='$userId'";
$result = mysqli_query($conn,$query);
$num = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
if($row["user_id"]==$userId){
if($row["password"]==$password){ //when user_id and password
//match, go to check
//usertype
switch($row["user_type_id"]){
case 1: session_start();
$_SESSION['erp']='true';
header('location:acc_setting.php');
break;
case 2: session_start();
$_SESSION['erp']='true';
header('location:dashboard.php');
break;
case 3: session_start();
$_SESSION['erp']='true';
header('location:c_course.php');
break;
}
}
else{
echo '<script language="javascript">';
echo 'alert("Invalid Password")';
echo '</script>';
}
}
else{
echo '<script language="javascript">';
echo 'alert("Invalid Username")';
echo '</script>';
}
}
?>
Ignoring the security issues I mentioned in comments and to specifically answer your subsequent question how do I set a session var and redirect it to same page perhaps the following might help. I simplified in a couple of places but essentially the same for the most part.
<?php
if( $_POST ){
session_start();
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'erp';
$conn = mysqli_connect( $host, $user, $pass, $db );
$destinations=array(
1 => 'acc_setting.php',
2 => 'dashboard.php',
3 => 'c_course.php'
);
$userId = $_POST['myusername'];
$password = $_POST['mypassword'];
/*
This should be a prepared statement
-> $sql='select `password` from `users` where `user_id`=?';
-> $stmt=$conn->prepare( $sql );
-> $stmt->bind_param('s',$userid );
etc etc
The passwords should be hashed in the db using password_hash
and verified in PHP using password_verify
NEVER store plain text passwords
*/
$query = "SELECT * from user where user_id='$userId'";
$result = mysqli_query($conn,$query);
$num = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
if( $row['user_id']==$userId ){
/*
this should be password_verify
*/
if( $row['password']==$password ){
$_SESSION['erp']='true';
exit( header( sprintf( 'Location: %s', $destinations[ $row['user_type_id'] ] ) ) );
} else{
$_SESSION['error']='Invalid Password';
}
} else{
$_SESSION['error']='Invalid Username';
}
/*
An error must have occurred, redirect back to oiginal page
*/
exit( header( sprintf('Location: %s', $_SERVER['SCRIPT_NAME'] ) ) );
}
?>
Then, in the original page where the form is
<form>
<!--
various form elements
-->
<?php
if( !empty( $_SESSION['error'] ) ){
echo $_SESSION['error'];
unset( $_SESSION['error'] );
}
?>
</form>

Error parsing JSON file - Incorrect Object

I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school

Save entire DOM in mysql

I am not sure if this is possible, but I am looking for a way to save the entire state of my webpage without explicitly saving each element to a database.
For example, I dynamically create buttons, checkboxes, text etc. until the webpage looks as it needs. Can I save the DOM as a string, or blob in a database, and parse it later the get the webpage back?
I have tried things like:
var doc = document.documentElement.outerHTML;
Then save the string to database but it doesn't work.
I am using an AJAX call to a PHP script to write to mysql:
jQuery.ajax({
type: "POST",
url: 'connect/database.php',
dataType: 'json',
data: {functionname: 'connect_to_database', arguments: [user_id, user, doc] },
success: function (obj, textstatus) {
if( !('error' in obj) ) {
}
else {
console.log(obj.error);
}
}
});
PHP looks like:
// connection script
$servername = "XXX";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
$user_id = $_POST['arguments'][0];
$user = $_POST['arguments'][1];
$string = $_POST['arguments'][2];
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table (user_id, user, string) VALUES ('$user_id', '$user', '$string')";
# $sql = "UPDATE crows_nest SET json_string='$configuration' WHERE user = '$user'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Use a prepared statement to prevent problems with special characters in the document string.
$stmt = $conn->prepare("INSERT INTO table (user_id, user, string) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $user_id, $user, $string);
if ($stmt->execute()) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

PHP password_verify() does not verify successfully

I have checked all the similar questions and answers but none is working for me.
I am using the standard php hashing and verification method Below are my codes.
this the code for hashing the password
$passwordhash = password_hash($pwd, PASSWORD_DEFAULT);
the hashed output is then stored into a mysql database table the column is varchar datatype with size 255.
When the hash is retrieved and verified with a user presented password the verification returns a false.
the code for the verification is presented below.
if($rows2['user_name'] == $username) && password_verify($password ,$rows2['password'])){
$_SESSION['login_user']=$username; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
however a verification of the hash with a correct password before storage provides a true answer.
here is the code for the verification before storage
if(password_verify($pwd ,$hashpassword )){
echo "<BR>"." the internal verify before storage"."<BR>";
}
this is the code for the storage of the hashed password.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "datacentre";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname , 3306);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//mysql_select_db("$database", $con);
$sql= "INSERT INTO admin (user_name , password , time_created)
VALUES ('$u_name' , '$hash' , NOW() )";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
This is the code for retrieving the hashed password.
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Create connection
$con = mysqli_connect($db_hostname, $db_username, $db_password, $db_database , 3306);
// Check connection
if(mysqli_connect_error()){
die("Connection failed: ".$con->connect_error);
}
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
// Retrieve data from database
$sql="select * from admin where user_name ='$username'";
$result = mysqli_query($con,$sql);
while($rows2 = $result->fetch_assoc()){
if($rows2['user_name'] == $username) && password_verify($password ,$rows2['password'])){
$_SESSION['login_user']=$username; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
$con->close(); // Closing Connection
}
}
}
looks like the problem is with how the database stores the hashed password.
Please will need a solution.

Redirect a logged in user from login page to user dashboard with php

I need your help to manage a php page with redirection function.
I want my logged in users to redirect to user dashboard instead of displaying login page by typing address in Browser's address Bar. How to prevent users to display login page
Login page codes are given below
<?php
include 'dbc.php';
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['user_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
if(empty($err)){
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
header("Location: dashboard.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
?>
I put your codes like this but got no effect. So please elaborate well and give example how to do it exactly.
<?php
include 'dbc.php';
if (isset ($_SESSION['status_logged']) && $_SESSION['status_logged'] = true) {
header('Location: dashboards.php');
}
else {
$_SESSION['status_logged'] = false;
}
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['user_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
if(empty($err)){
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
$_SESSION['status_logged'] = true; //new line
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
header("Location: dashboard.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
?>
You already have a session with the user data, so, it's simple, save the status in the same session and make a verification on the top of your script. Like this
Put this in your code
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
$_SESSION['status_logged'] = true; //new line
And put a verification on the top:
if (isset ($_SESSION['status_logged']) && $_SESSION['status_logged'] == true) {
header('Location: yourDashboardPage.php');
}
else {
$_SESSION['status_logged'] = false;
}

Categories