when click php in my domain [duplicate] - php

This question already has answers here:
Apache is downloading php files instead of displaying them
(27 answers)
Closed 5 years ago.
i'm having a problem to my website when i'm clicking it , its just downloading and not even loading for the next page. what can i do? what should i change? i'm just a newbie in html and php , by the way the file i was click is a php file that i made and it is not directing to next page the file was downloading when i click that php file. i was wondering if someone help me here , thanks in advance for someone who might help me. it is just for my project. http://itweb.bitballoon.com/
this is the website when i'm clicking the sign and register it will download the file of php i dont know how to solve this problem i search already in youtube and google. i cant see a single answer. someone help me please thanks.
codes of register.php
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$firstname = trim($_POST['firstname']);
$firstname = strip_tags($firstname);
$firstname = htmlspecialchars($firstname);
$middlename = trim($_POST['middlename']);
$middlename = strip_tags($middlename);
$middlename = htmlspecialchars($middlename);
$lastname = trim($_POST['lastname']);
$lastname = strip_tags($lastname);
$lastname = htmlspecialchars($lastname);
$student_number = trim($_POST['student_number']);
$student_number = strip_tags($student_number);
$student_number = htmlspecialchars($student_number);
$course = $_POST['course'];
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// basic name validation
if (empty($firstname)) {
$error = true;
$firstnameError = "Please enter your firstname.";
} else if (strlen($firstname) < 2) {
$error = true;
$firstnameError = "Firstname must have atleat 2 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$firstname)) {
$error = true;
$firstnameError = "Firstname must not contain numbers or special characters.";
}
if (!empty($middlename) && !preg_match("/^[a-zA-Z ]+$/",$middlename)) {
$error = true;
$middlenameError = "Middlename must not contain numbers or special characters.";
}
if (empty($lastname)) {
$error = true;
$lastnameError = "Please enter your lastname.";
} else if (strlen($lastname) < 2) {
$error = true;
$lastnameError = "Lastname must have atleat 2 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$lastname)) {
$error = true;
$lastnameError = "Lastname must not contain numbers or special characters.";
}
if (empty($course)) {
$error = true;
$courseError = "Please select a course.";
}
if (empty($student_number)) {
$error = true;
$student_numberError = "Please enter your student number.";
} else if (!(strlen($student_number) >= 12 && strlen($student_number) <= 13)) {
$error = true;
$student_numberError = "Student number must have atleat 12 characters.";
} else if (!preg_match("/^PM-[0-9]{2}-[0-9]{4,5}-[AB]$/", $student_number)) {
$error = true;
$student_numberError = "Invalid student number format.";
} else {
//check if student number exists
$result = mysql_query("SELECT * FROM users WHERE student_number = '$student_number'");
$rowCount = mysql_num_rows($result);
if ($rowCount == 1) {
$error = true;
$student_numberError = "Student number is already taken.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
// password encrypt using SHA256();
$password = hash('sha256', $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO users(student_number,userPass,user_role,firstname,middlename,lastname,course) VALUES('$student_number','$password',2,'$firstname','$middlename','$lastname',$course)";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now.";
unset($firstname);
unset($middlename);
unset($lastname);
unset($course);
unset($student_number);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="assets/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#course').change(function () {
if ($(this).val() == '') {
$(this).css('color', '#999');
}
else {
$(this).css('color', '#000');
}
$('option').css('color', '#000');
});
$('#course').trigger('change');
});
</script>
</head>
<body>
<div class="container">
<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<div class="col-md-12">
<div class="form-group">
<h2 class="">Sign Up.</h2>
</div>
<div class="form-group">
<hr />
</div>
<?php
if ( isset($errMSG) ) {
?>
<div class="form-group">
<div class="alert alert-<?php echo ($errTyp=="success") ? "success" : $errTyp; ?>">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
</div>
</div>
<?php
}
?>
<div class="form-group">
<div class="input-group ">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="firstname" class="form-control" placeholder="Firstname" maxlength="50" value="<?php echo $firstname ?>" />
</div>
<span class="text-danger"><?php echo $firstnameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="middlename" class="form-control" placeholder="Middlename" maxlength="50" value="<?php echo $middlename ?>" />
</div>
<span class="text-danger"><?php echo $middlenameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="lastname" class="form-control" placeholder="Lastname" maxlength="50" value="<?php echo $lastname ?>" />
</div>
<span class="text-danger"><?php echo $lastnameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-book"></span></span>
<select id="course" name="course" class="form-control">
<option <?php echo $course == "1" ? "selected" : "" ?> value="1">BSIT</option>
<option <?php echo $course == "2" ? "selected" : "" ?> value="2">BSBA</option>
<option <?php echo $course == "3" ? "selected" : "" ?> value="3">BSTM</option>
<option <?php echo $course == "4" ? "selected" : "" ?> value="4">BSHRM</option>
<option <?php echo $course == "5" ? "selected" : "" ?> value="5">BSN</option>
<option <?php echo $course == "6" ? "selected" : "" ?> value="6">BSC</option>
<option <?php echo $course == "7" ? "selected" : "" ?> value="7">BSA</option>
<option <?php echo $course == "8" ? "selected" : "" ?> value="8">BSE</option>
<option <?php echo $course == "9" ? "selected" : "" ?> value="9">ABMC</option>
<option <?php echo $course == "10" ? "selected" : "" ?> value="10">BSP</option>
<option <?php echo $course == "11" ? "selected" : "" ?> value="11">BAPA</option>
</select>
</div>
<span class="text-danger"><?php echo $courseError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="student_number" class="form-control" placeholder="Student Number" maxlength="50" value="<?php echo $student_number ?>" />
</div>
<span class="text-danger"><?php echo $student_numberError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" name="pass" class="form-control" placeholder="Password" maxlength="15" />
</div>
<span class="text-danger"><?php echo $passError; ?></span>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-signup">Sign Up</button>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
Sign in Here...
</div>
</div>
</form>
</div>
</div>
</body>
</html>
<?php ob_end_flush(); ?>
Sign in codes :
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if ( isset($_SESSION['user'])!="" ) {
header("Location: home.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$student_number = trim($_POST['student_number']);
$student_number = strip_tags($student_number);
$student_number = htmlspecialchars($student_number);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($student_number)){
$error = true;
$student_number_Error = "Please enter your student number.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT student_number, userPass, user_role, firstname, middlename, lastname, course FROM users WHERE student_number = '$student_number'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['student_number'];
header("Location: home.php");
echo $_GET['id'];
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="container">
<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<div class="col-md-12">
<div class="form-group">
<h2 class="">Sign In.</h2>
</div>
<div class="form-group">
<hr />
</div>
<?php
if ( isset($errMSG) ) {
?>
<div class="form-group">
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
</div>
</div>
<?php
}
?>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="student_number" class="form-control" placeholder="Student Number" value="<?php echo $student_number; function a(){$student_number=$idc;}?>" maxlength="15" />
</div>
<span class="text-danger"><?php echo $student_number_Error; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" name="pass" class="form-control" placeholder="Password" maxlength="30" />
</div>
<span class="text-danger"><?php echo $passError; ?></span>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
Sign Up Here...
</div>
</div>
</form>
</div>
</div>
</body>
</html>
<?php ob_end_flush(); ?>
Error message is: Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /storage/ssd5/266/3359266/public_html/dbconnect.php:11 Stack trace: #0 /storage/ssd5/266/3359266/public_html/login.php(4): require_once() #1 {main} thrown in /storage/ssd5/266/3359266/public_html/dbconnect.php on line 11

You need to check with the website hosting server whether it support PHP. And check is it configured correctly in the server.

Related

Database query and hashed password for a database login

I've been following the code provided by https://dzone.com/articles/ceate-a-login-system-using-html-php-and-mysql to create a login system for my database. I can register an account with no problems, but when I try to login using the credentials I just entered in the register page I get an invalid password message. At first I thought it was a hashed password issue that I was messing up because of the invalid password error but now it almost seems like it's not processing the query correctly because when I add a print_r($query) I get mysqli_stmt Object ( [affected_rows] => -1 ... printed out to the page. Does anyone see where I'm going amiss? Here is the code that I'm using for the login.
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
if (empty($email)) {
$error .= '<p class="error">Please enter your email.</p>';
}
if (empty($password)) {
$error .= '<p class="error">Please enter your password.</p>';
}
if (empty($error)) {
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s', $email);
$query->execute();
$row = $query->fetch();
print_r($query);
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$_SESSION["user"] = $row;
header("location: welcome.php");
exit;
} else {
echo("Password invalid<br><br>");
$error .= '<p class="error">The password is not valid.</p>';
}
} else {
echo("Email invalid");
$error .= '<p class="error">Email address is incorrect.</p>';
}
}
$query->close();
}
mysqli_close($db);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Login</h2>
<p>Please enter your email and password.</p>
<form action="" method="post">
<div class="form-group">
<label>Email Address</label>
<input type="email" name="email" class="form-control" required />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
<p>Don't have an account? Register here.</p>
</form>
</div>
</div>
</div>
</body>
</html>
And here is the code for the register.php
<?php
require_once "config.php";
require_once "session.php";
if ($_SERVER["REQUEST_METHOD"]=="POST" && isset($_POST['submit'])) {
$fullname = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$error = '';
$query->bind_param('s',$email);
$query->execute();
$query->store_result();
if ($query->num_rows > 0) {
$error .= '<p class="error">The email address is already registered!</p>';
} else {
if (strlen($password ) < 6) {
$error .= '<p class="error">Password must have at least 6 characters.</p>';
}
if (empty($confirm_password)) {
$error .= '<p class="error">Please enter confirm password.</p>';
} else {
if (empty($error) && ($password != $confirm_password)) {
$error .= '<p class="error">Passwords do not match.</p>';
}
}
if (empty($error) ) {
$insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);");
$insertQuery->bind_param("sss", $fullname, $email, $password_hash);
$result = $insertQuery->execute();
if ($result) {
$error .= '<p class="success">Your registration was successful!</p>';
} else {
$error .= '<p class="error">Something went wrong!</p>';
}
echo($password);
}
}
}
$query->close();
$insertQuery->close();
mysqli_close($db);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col=md=12">
<h2>Register</h2>
<p>Please complete this form to create an account.</p>
<form action="" method="post">
<div class="form-group">
<label> Full Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group">
<label>Email Address</label>
<input type="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</div>
</div>
</body>
</html>

post/redirect/get - how to unset session variables

Bellow is part of the code from register.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
/* running some checks of an input*/
if(sizeof($errorArray)==0) {
// redirecting to avoid form resubmission
$_SESSION['registered'] = true;
header('location: success.php',true,303);
}
else{
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['errorArray'] = $errorArray;
header('location: register.php',true,303);
}
}
Logic is simple -- if an errorArray is empty redirect to a success page, else redirect to register.php itself. To avoid form resubmission i tried to put post variables into session variable, so the user doesn't have to fill form again in case of error.
<?php
if (isset($_SESSION['errorArray'])) {
if (sizeof($_SESSION['errorArray']) != 0) {
echo '<div class="alert alert-danger" role="alert">
<h4>There were errors in Your input:</h4>';
foreach ($_SESSION['errorArray'] as $item) {
echo $item . '<br>';
}
}
$_SESSION['post'] = null;
$_SESSION['errorArray'] = null;
}
?>
This part of a code is executed later in register.php but it doesen't gives me the result I want. Somehow the variables are sett to null before the loop above is executed (??!). I have found a solution with get method that includes microtime in url passed to header , but it seams to me that there is more elegant solution that does not every time adds new values to a session variable.
Is there some way around this?
edit :
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// array to hold all the errors of input
$errorArray = [];
$emailRegex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
$nameRegex = '/^[a-z0-9][a-z0-9_]*[a-z0-9]$/';
$passwordRegex = '/^[a-z0-9][-a-z0-9_!##$?]*[a-z0-9]$/';
$email = $_POST['email'];
if (empty($email)) {
array_push($errorArray, "E-mail field required");
} else {
if (!preg_match($emailRegex, $email)) array_push($errorArray, 'Invalid email');
}
$name = $_POST['name'];
if (empty($name)) {
array_push($errorArray, "Name field required");
} else {
if (!preg_match($nameRegex, $name)) array_push($errorArray, 'Invalid name');
}
$password = $_POST['password'];
$passwordR = $_POST['passwordR'];
if (empty($passwordR) || empty($password)) {
array_push($errorArray, 'Password fields required');
} else if (!preg_match($passwordRegex, $password)) {
array_push($errorArray, 'Invalid password');
} else {
if ($password !== $passwordR) {
array_push($errorArray, 'Password inputs are not the same');
}
}
if (sizeof($errorArray) == 0) {
// redirecting to avoid form resubmission
$_SESSION['registered'] = true;
header('location: success.php', true, 303);
} else {
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['errorArray'] = $errorArray;
header('location: register.php', true, 303);
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Log</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="css/maincss.css" type="text/css">
<meta name="viewport" content="width = device-width, initial-scale = 1, user - scalable = no">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed">
<div class="container">
Home
<ul class="navbar-brand col-xs-5"><?= (isset($username)) ? 'Welcome ' . $username : ''; ?></ul>
Login
Register
</div>
</nav>
<div class="container">
<form class="form-signin" action="register.php" method="post">
<h2 class="form-signin-heading text-center text-capitalize">Registration form</h2>
<!-- I have purposely excluded required attribute from inputs and set type="text"
for an email so all the checks could be done on server side -->
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="email" class="sr-only">Email address</label>
<input type="text" id="email" name="email" class="form-control" placeholder="Email address"
value="<?= (isset($_SESSION['post']['email'])) ? $_SESSION['post']['email'] : ''; ?>" autofocus>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="name" class="sr-only">Name</label>
<input type="text" id="name" name="name" class="form-control" placeholder="Name"
value="<?= (isset($_SESSION['post']['name'])) ? $_SESSION['post']['name'] : ''; ?>" autofocus>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password">
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="passwordR" class="sr-only">Repeat Password</label>
<input type="password" id="passwordR" name="passwordR" class="form-control"
placeholder="Repeat Password">
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row">
<div class="col-xs-4"></div>
<div class="col-xs-4 center-block">
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div>
<?php
if (isset($_SESSION['errorArray'])) {
if (sizeof($_SESSION['errorArray']) != 0) {
echo '<div class="alert alert-danger" role="alert">
<h4>There were errors in Your input:</h4>';
foreach ($_SESSION['errorArray'] as $item) {
echo $item . '<br>';
}
}
// $_SESSION['post'] = null;
// $_SESSION['errorArray'] = null;
}
?>
</div>
</form>
</body>
</html>

Validation Display in Registration form with Bootstrap

In the following code in crudindex.php if I enter password with length less than 6 characters error message is not showing using the span command.Required pattern is working. But messages using span command is not displaying ex : if i enter length less than 6 in password no error message displays
What is wrong in this code?
<?php
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "", "kkits996_testmysql") or die("Error " . mysqli_error($con));
$error=false;
if (isset($_POST) && (!empty($_POST))){
$uname=mysqli_real_escape_string($con,$_POST["uname"]);
$pwd=mysqli_real_escape_string($con,$_POST["pwd"]);
$cpwd=mysqli_real_escape_string($con,$_POST["cpwd"]);
$password_error="";
$cpassword_error="";
if(strlen($pwd) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($pwd != $cpwd) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (isset($_POST['register'])) {
# Register-button was clicked
$createsql1="INSERT INTO cruduser(id,username,password) VALUES
('','$uname','$pwd')";
if (mysqli_query($con,$createsql1)) {
echo "Insert Successful in Table cruduser";
mysqli_close($con);
//Redirect because we need to consider the post request from crudadd.php
header( 'Location: crudaddusr.php' ) ;
//include ("crudadd.php");
}
else
{
die(mysqli_error($con));
}
}
if (isset($_POST['login'])) {
# Login-button was clicked
session_start();
$SESSION['suname']=$uname;
$SESSION['spwd']=$pwd;
if ($uname=='admin' && $pwd=='admin') {
include('crudview.php');
}
else
{
header( "Location: crudeditusr.php?suname=$uname&spwd=$pwd");
}
}
mysqli_close($con);
}
?>
<!--DocType HTML -->
<! bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<! col-mod-6 col-mod-offset are bootstrap related-->
<HTML>
<head>
<title>"Add records in CRUD Table"</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" class="form-horizontal col-mod-6 col-mod-offset-3">
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Username : </label>
<div class="col-sm-10">
<input type="text" name="uname" required pattern="^[A-Za-z0-9]+" class="form-control" id="input1" placeholder="Username"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Password: </label>
<div class="col-sm-10">
<input type="password" name="pwd" required pattern="^[A-Za-z0-9]+" class="form-control" id="input1" placeholder="Password"/>
<span class="error"><?php if (isset($password_error)) echo $password_error;?></span>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Confirm Password : </label>
<div class="col-sm-10">
<input type="password" name="cpwd" required pattern="^[A-Za-z0-9]+" class="form-control" id="input1" placeholder="Confirm Password"/>
<span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
</div>
</div>
<div class="row">
<div class="col-mod-6 col-mod-offset-3">
<button id="submit1" name="register" class="btn btn-primary pull-right">Register</button>
<button id="submit2" name="login" class="btn btn-secondary pull-right">Login</button>
</div>
</div>
</form>
</body>
</html>
This is a working example to display your errors and prevent some security problems. I have removed the required pattern from your html. You didn't properly set errors. You can handle errors with php and display them. Plus you didn't use action="path/to/handleform.php".
And your redirect should be in login: header( "Location: crudeditusr.php?suname=".$uname."&spwd=".$pwd);
There are 3 security problems here:
SQL injection. SOLUTION=> prepared statement
Password saved as plain text. SOLUTION=> password_hash()
Cross-Site Request Forgery (CSRF). SOLUTION=> input hidden with a token
<?php
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "", "kkits996_testmysql") or die("Error " . mysqli_error($con));
// Declare array for errors
$error=array();
//-----------------------------------------------------//
//---------------------CSRF PROTECT--------------------//
//-----------------------------------------------------//
//generate a token/
function generateToken( $formName )
{
//secret_key change it
$secretKey ='?#GEskki58668445744!Erpoejsj48';
if ( !session_id() )
{
session_start();
}
$sessionId = session_id();
return hash('sha512', $formName.$sessionId.$secretKey );
}
//check if the token is valid
function checkToken( $token, $formName)
{
return $token === generateToken( $formName );
}
//Separate REGISTER AND LOGIN TO NOT BE CONFUSED//
//-----------------------------------------------------//
//---------------------REGISTRATION--------------------//
//-----------------------------------------------------//
if ( isset($_POST['register']) && checkToken( $_POST['csrf_token'], 'userFromRegistration' ) )
{
//if the username required
if(!preg_match('/^[A-Za-z0-9]+$/',$_POST['uname']))
{
$error['username'] = "Username must have alphanumeric characters ";
}
//if password has less than 6 characters
if(strlen($_POST['pwd']) < 6)
{
$error['password'] = "Password must be minimum of 6 characters";
}
//if password does not match
if($_POST['pwd'] !== $_POST['cpwd'] OR empty($_POST['cpwd']) )
{
$error['passwordmatch'] = "Password and Confirm Password doesn't match";
}
//if empty error array
if( !array_filter($error) )
{
//trim data
$username = trim( $_POST['uname'] );
// Hash you password, never save PASSWORD AS PLAIN TEXT!!!!!!!
// MYSQL! : Allow your storage to expand past 60 characters (VARCHAR 255 would be good)
$password = password_hash( $_POST['pwd'], PASSWORD_DEFAULT);
//if the id is autoincremented leave id
//----------USE PREPARED STATEMENT FOR SQL INJECTION---//
$query = 'INSERT INTO cruduser (username, password) VALUES (?,?)';
$stmt = $con->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->close();
$con->close();
//Redirect because we need to consider the post request from crudadd.php
header( 'Location: crudaddusr.php' ) ;
}
}
//-----------------------------------------------------//
//------------------------LOGIN------------------------//
//-----------------------------------------------------//
if (isset($_POST['login']))
{
//what ever you want
//Use password_verify() and session_regenerate_id()
//to compare passwords and to generate a session id to prevent session fixation.
session_start();
$uname = $_POST['uname'];
$pwd = $_POST['pwd'];
//if you don't need it delete it
$SESSION['suname']=$unmane;
$SESSION['spwd']=$pwd;
if ($uname=='admin' && $pwd=='admin')
{
include('crudview.php');
}
else
{
header( "Location: crudeditusr.php?suname=".$uname."&spwd=".$pwd);
}
}
?>
<!--HTMl PART-->
<!DOCTYPE html>
<html>
<head>
<title>"Add records in CRUD Table"</title>
<!-- bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<!-- col-mod-6 col-mod-offset are bootstrap related-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" action="" class="form-horizontal col-mod-6 col-mod-offset-3">
<input type="hidden" name="csrf_token" value="<?php echo generateToken('userFromRegistration'); ?>" required/>
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Username : </label>
<div class="col-sm-10 <?php if( !empty( $error['username'] ) ){ echo 'has-error';} ?> ">
<input type="text" name="uname" class="form-control" id="input1" placeholder="Username"/>
<span class="help-block"><?php if (!empty($error['username'])) echo $error['username'];?></span>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Password: </label>
<div class="col-sm-10 <?php if( !empty( $error['password'] ) ){ echo 'has-error';} ?>">
<input type="password" name="pwd" class="form-control" id="input1" placeholder="Password"/>
<span class="help-block"><?php if (!empty($error['password'])) echo $error['password'];?></span>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Confirm Password : </label>
<div class="col-sm-10 <?php if( !empty( $error['passwordmatch'] ) ){ echo 'has-error';} ?>">
<input type="password" name="cpwd" class="form-control" id="input1" placeholder="Confirm Password"/>
<span class="help-block"><?php if (!empty($error['passwordmatch'])) echo $error['passwordmatch'];?></span>
</div>
</div>
<div class="row">
<div class="col-mod-6 col-mod-offset-3">
<button id="submit1" name="register" class="btn btn-primary pull-right">Register</button>
<button id="submit2" name="login" class="btn btn-secondary pull-right">Login</button>
</div>
</div>
</form>
</body>
Change this line from this,
$pwd=mysqli_real_escape_string($con,$_POST["pwd"]);
to this,
$pwd=mysqli_real_escape_string($_POST["pwd"]);
You don't need to add $con to assign your password to another variable but it's better use the direct $_POST variable no need to assign it to another.
if(strlen($_POST["pwd"]) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}

Can't get login script to work after adding salt to hash; worked fine before

I've reset my database and on registration, we added random salt to hashes, and the registration script worked fine, we could create accounts and accounts with the same password and they had different hashes, but our login script is broken, not logging in users, saying their password is incorrect.
No idea why- we have spent the last 2 hours trying to fix it. We have used PHP error checkers(https://phpcodechecker.com/), nothing was wrong.
We are running an old version PHP(5.6) and MySQL and can't currently change.
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: index.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($name)){
$error = true;
$nameError = "Please enter your username.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
$res=mysql_query("SELECT userId, userEmail, userPass, userSalt, userSalt2 FROM users WHERE userName='$name'");
$row=mysql_fetch_array($res);
$row['userSalt']=$salt1;
$row['userSalt2']=$salt2;
// if there's no error, continue to login
if (!$error) {
$passwordHash = hash('sha256', $salt1 . $password . $salt2); // password hashing using SHA256
//$res=mysql_query("SELECT userId, userEmail, userPass, userSalt, userSalt2 FROM users WHERE userName='$name'");
//$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if email/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$passwordHash ) {
$_SESSION['user'] = $row['userId'];
header("Location: dashboard.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$("#overallhead").load("overall_header.php");
$("#overallfoot").load("overall_footer.html");
});
</script>
<style>
body {
color: Thistle;
}
</style>
<div id="overallhead"></div>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Creature Paradise</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="container">
<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<div class="col-md-12">
<div class="form-group">
<h2 class="">Login</h2>
</div>
<div class="form-group">
<hr />
</div>
<?php
if ( isset($errMSG) ) {
?>
<div class="form-group">
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
</div>
</div>
<?php
}
?>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input type="name" name="name" class="form-control" placeholder="Your Username" value="<?php echo $name; ?>" maxlength="40" />
</div>
<span class="text-danger"><?php echo $nameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" />
</div>
<span class="text-danger"><?php echo $passError; ?></span>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
Don't have an account? Sign up here!
</div>
</div>
</form>
</div>
</div>
<div id="overallfoot"></div>
</body>
</html>
<?php ob_end_flush(); ?>
Have you do hashing on registration page, too? Because $row['userPass'] will never equal $passwordHash if you have not registration a new account with new hash applied

How to update or delete data in php mysql

I created a table to view records from database, i am unable to update or delete, nothing happens if I click on the buttons they are just redirected without the changes..what can be done to fix this.
update.php
<?php
include 'includes/db.php';
//$student_id = null;
if ( !empty($_GET['student_id'])) {
$student_id = $_REQUEST['student_id'];
}
if ( null==$student_id ) {
header("Location: addstudent.php");
}
if ( !empty($_POST)) {
// keep track valstudent_idation errors
$first_nameError = null;
$middle_nameError = null;
$last_nameError = null;
$emailError = null;
$idcodeError = null;
// keep track post values
$first_name = $_POST['first_name'];
$middle_name = $_POST['middle_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$idcode = $_POST['idcode'];
// validate input
$valstudent_id = true;
if (empty($first_name)) {
$nameError = 'Please enter Name';
$valstudent_id = false;
}
$valstudent_id = true;
if (empty($middle_name)) {
$nameError = 'Please enter Name';
$valstudent_id = false;
}
$valstudent_id = true;
if (empty($last_name)) {
$nameError = 'Please enter Name';
$valstudent_id = false;
}
if (empty($email)) {
$emailError = 'Please enter Email Address';
$valstudent_id = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Please enter a valid Email Address';
$valstudent_id = false;
}
if (empty($idcode)) {
$idcodeError = 'Please enter IDCODE';
$valstudent_id = false;
}
// update data
if ($valstudent_id) {
$first_name=$_POST['first_name'];
$middle_name=$_POST['middle_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$idcode=$_POST["idcode"];
$sql = "UPDATE student SET first_name=:first_name, middle_name=:middle_name, last_name=:last_name, idcode=:idcode, email=:email WHERE student_id=:student_id";
$stmt = $pdo->prepare($sql);
//echo "<br/>Query: ".$stmt->query()."<br/>"
$stmt->bindValue(':first_name', $first_name);
$stmt->bindValue(':middle_name', $middle_name);
$stmt->bindValue(':last_name', $last_name);
$stmt->bindValue(':idcode', $idcode);
$stmt->bindValue(':email', $email);
$result= $stmt->execute();
//$result = execute(array($first_name,middle_name,last_name,$email,$idcode));
header("Location: table.php");
}
}
else {
$sql = "SELECT * FROM student where student_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($student_id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$first_name = $data['first_name'];
$middle_name = $data['middle_name'];
$last_name = $data['last_name'];
$idcode = $data['idcode'];
$email = $data['email'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update People</h3>
</div>
<form class="form-horizontal" action="update.php?student_id=<?php echo $student_id?>" method="post">
<div class="control-group <?php echo !empty($first_nameError)?'error':'';?>">
<label class="control-label">First Name</label>
<div class="controls">
<input name="first_name" type="text" placeholder="first_Name" value="<?php echo !empty($first_name)?$first_name:'';?>">
<?php if (!empty($first_nameError)): ?>
<span class="help-inline"><?php echo $middle_nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Middle Name</label>
<div class="controls">
<input name="middle_name" type="text" placeholder="middle_Name" value="<?php echo !empty($middle_name)?$middle_name:'';?>">
<?php if (!empty($middle_nameError)): ?>
<span class="help-inline"><?php echo $middle_nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Last Name</label>
<div class="controls">
<input name="last_name" type="text" placeholder="last_Name" value="<?php echo !empty($last_name)?$last_name:'';?>">
<?php if (!empty($last_nameError)): ?>
<span class="help-inline"><?php echo $lastnameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($emailError)?'error':'';?>">
<label class="control-label">Email Address</label>
<div class="controls">
<input name="email" type="text" placeholder="Email Address" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-inline"><?php echo $emailError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($idcodeError)?'error':'';?>">
<label class="control-label">IDCODE</label>
<div class="controls">
<input name="idcode" type="text" placeholder="IDCODE" value="<?php echo !empty($idcode)?$idcode:'';?>">
<?php if (!empty($idcodeError)): ?>
<span class="help-inline"><?php echo $idcodeError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="table.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
delete.php
<?php
error_reporting(1);
include 'includes/db.php';
$student_id = 0;
if ( !empty($_GET['student_id'])) {
$student_id = $_REQUEST['student_id'];
}
if ( !empty($_POST)) {
$id = $_POST['student_id'];
// delete data
$sql = "DELETE FROM people WHERE student_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($student_id));
header("Location: table.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Delete the Person</h3>
</div>
<form class="form-horizontal" action="delete.php" method="post">
<input type="hidden" name="student_id" value="<?php echo $student_id;?>"/>
<p class="alert alert-error">Are you sure to delete ?</p>
<div class="form-actions">
<button type="submit" class="btn btn-danger">Yes</button>
<a class="btn" href="table.php">No</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>

Categories