Why don't my error messages display on my form? - javascript

<?php
session_start();
require_once "../connector.php";
$errors = array();
if(isset($_POST["create"])){
$fname = $_POST['fname'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$cpass = $_POST['cpass'];
if($fname == "" || $email == "" || $pass == "" || $cpass == ""){
$errors['fname'] = "Please enter your full name.";
$errors['email'] = "Please enter your email address.";
$errors['pass'] = "Please enter a password.";
$errors['cpass'] = "Please confirm your password.";
header("Location:createaccountform.php");
}else{
$usercheckquery = "SELECT * FROM userdetails WHERE EMAIL_ADDRESS = '$email'";
$result = mysqli_query($conn, $usercheckquery);
if(mysqli_num_rows($result)>0){
$errors['email'] = "This email already exists. Please use another one.";
header("Location:createaccountform.php");
}
else if(!preg_match("/^[a-zA-Z ]*$/",$fname)){
$errors['email'] = "Please enter a valid full name.";
header("Location:createaccountform.php");
}
else if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)){
$errors['email'] = "This email format is invalid.";
header("Location:createaccountform.php");
}
else if(strlen($pass) < 8){
$errors['email'] = "Your password must have a minimum of 8 characters";
header("Location:createaccountform.php");
}
else if($cpass != $pass){
$errors['email'] = "The passwords do not match.";
header("Location:createaccountform.php");
}
else{
$hashedpassword = password_hash($pass, PASSWORD_DEFAULT);
$sql = "INSERT INTO `loginundregistration`.`userdetails`(`FULLNAME`,`EMAIL_ADDRESS`,`USERPASSWORD`)
VALUES ('$fname','$email','$hashedpassword')";
$query = mysqli_query($conn, $sql);
if($query){
//$message = "Created account successfully";
header("Location:createaccountform.php");
}
else{
//$message = "Error creating account. Please try again";
header("Location:createaccountform.php");
}
}
}
}
header('Content-Type: application/json');
echo json_encode($errors);
?>
form.addEventListener("submit", function (e) {
e.preventDefault();
const data = new FormData(form);
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "register.php", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.onload = function () {
if (this.status === 200) {
let response = JSON.parse(xhttp.responseText);
console.log(response);
for (const key in response) {
const errorID = key + '-error';
const errorMessage = response[key];
const errorSmall = document.getElementById(errorID);
if (errorMessage) {
errorSmall.innerHTML = errorMessage;
errorSmall.classList.remove('success');
errorSmall.classList.add('error');
} else {
errorSmall.innerHTML = '';
errorSmall.classList.remove('error');
errorSmall.classList.add('success');
}
}
}
};
xhttp.send(data);
});
form.addEventListener('click', function (e) {
const target = e.target;
if (target.type === 'text' || target.type === 'email' || target.type === 'password') {
const errorID = target.id + '-error';
const errorSmall = document.getElementById(errorID);
errorSmall.innerHTML = '';
errorSmall.classList.remove('error');
errorSmall.classList.add('success');
}
});
<!DOCTYPE html>
<?php
require_once "../connector.php";
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<!--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css"/>-->
<script src="https://kit.fontawesome.com/c90e5c3147.js" crossorigin="anonymous"></script>-
<title>Create an Account</title>
</head>
<body>
<div class="container">
<div class="header">
<h2>Create Account</h2>
</div>
<form class="form" action = "register.php" method="POST" id="form" name="form">
<div class="form-control">
<label>Full Name</label>
<input type="text" placeholder="Please enter your full name" id="fname" name="fname">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small id="fname-error"></small>
</div>
<div class="form-control">
<label>Email Address</label>
<input type="email" placeholder="Please enter your email address" id="email" name="email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small id="email-error"></small>
</div>
<div class="form-control">
<label>Password</label>
<input type="password" placeholder="Please enter a password" id="pass" name="pass">
<i class="fa-solid fa-eye-slash" id="togglePass"></i>
<small id="pass-error"></small>
</div>
<div class="form-control">
<label>Confirm Password</label>
<input type="password" placeholder="Please confirm your password" id="cpass" name="cpass">
<i class="fa-solid fa-eye-slash" id="toggleCPass"></i>
<small id="cpass-error"></small>
</div>
<input type="hidden" value="Create Account" name="create">
<button id="createbtn" name="createbtn">Create Account</button>
</form>
</div>
<script src="js/script.js"></script>
</body>
</html>
.form-control.success input{
border-color: #2ecc71;
}
.form-control.error input{
border-color: #e74c3c;
}
.form-control i{
position: absolute;
top: 40px;
right: 10px;
visibility: hidden;
}
.form-control.success i.fa-check-circle{
color: #2ecc71;
visibility: visible;
}
.form-control.error i.fa-exclamation-circle{
color: #e74c3c;
visibility: visible;
}
.form-control small{
visibility: hidden;
position: absolute;
bottom: 0;
left: 0;
}
.form-control.success small{
color: #2ecc71;
}
.form-control.error small{
color: #e74c3c;
}
The code above is as simple registration form. I wrote some code to take server side PHP validation through AJAX and JSON and show it to the user through error messages on the form. I also added CSS to make the messages look better. The first part of code is the PHP where I store the message in an array called $errors and turn it into JSON string. The next is the JavaScript file where the JSON is parsed using AJAX and the JavaScript adds a class name to the HTML to show the correct CSS properties. The last two parts are the HTML and CSS. it doesn't display anything unfortunately. Even when I console the parsed JSON it is just an empty array. Any clue on why it doesn't work and how to fix it?

Related

Having Problem with my PHP Code and Jquery

I need some help
Whenever I input all the information and wanted to click submit, it always alert me "You already submit before" but it was the first time i entered the information. So there shouldn't be any duplicate values.
And the data itself also didn't post into my phpmyadmin database.
Secondly, i added the addclass("error") and removeclass ('error') in the javascript. However only those selection questions will show the red error border line while text input questions didn't show the error border line even though it is wrong
I have spent days to investigate it but still couldn't solve it.
My index.php file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Refund Request Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css" >
<!-- <script src="form.js"></script>-->
</head>
<body>
<div class="container">
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="form-container">
<span style="text-align: center;padding-bottom: 0px;"><br>
<center>
<h1>
Refund Request Form
</h1>
</center>
</span>
<form method="post" id="form" name="form">
<label for="school_num">School Number: <span class="required">*</span></label>
<input id="school_num" type="text" placeholder="Enter your School Number" name="school_num" maxlength="50">
<label for="name">Full Name: <span class="required">*</span></label>
<input id="name" type="text" placeholder="Enter your Name in Capital as per IC" name="name" maxlength="50">
<label for="email">Email Address: <span class="required">*</span></label>
<input id="email" type="text" placeholder="Enter your Email Address" name="email" maxlength="50">
<label for="ic_num">IC Number: <span class="required">*</span></label>
<input id="ic_num" type="number" placeholder="Enter your IC Number (without dash)" name="ic_num" data-parsley-length="[12,12]" maxlength="12">
<label for="nts">Event1 Refund Amount: <span class="required">*</span></label>
<select id="nts" placeholder="-" name="nts" onchange="sum()" >
<option value = "-" selected>-</option>
<option value = "0" >0</option>
<option value = "80">80</option>
<option value = "100">100</option>
<option value = "110">110</option>
<option value = "110">120</option>
</select>
<label for="pesta">Event2 Refund Amount: <span class="required">*</span></label>
<select id="pesta" placeholder="" name="pesta" onchange="sum()" >
<option value = "-" selected>-</option>
<option value = "0" >0</option>
<option value = "100">100</option>
<option value = "360">360</option>
<option value = "450">450</option>
<option value = "460">460</option>
<option value = "535">535</option>
<option value = "540">540</option>
</select>
<label for="remarks">Remarks:</label>
<textarea id="remarks" name="remarks" placeholder="Type your remarks here" rows="5" maxlength="6000"></textarea>
<label style="border-bottom:1px dotted grey; padding-top: 30px;" colspan="2"></label>
<label for="refund" class="refund" style="color:#faa51a;font-family: 'Open Sans', sans-serif;font-weight: 500; font-size: 150%;width: 30%">Refund Total: </label>
<input id="refund" class="refund1" value="0" readonly style="border:none;color:#faa51a;font-family: 'Open Sans', sans-serif;font-weight: 500;font-size: 150%;width: 20%">
<!-- <input type="hidden" id="refund" name="refund" class="refund1" value="0" > -->
<input class="button-primary" name="submit" id="submit" role="button" type="button" onClick="validateForm()" value="Submit">
<!-- <input type="button" class="button-primary" type="submit" name="submit" id="submit" role="button" value="Submit">-->
</form>
<div id="success_message" style="display:none">
<h3>Submitted the form successfully!</h3>
<p> We will get back to you soon. </p>
</div>
<div id="error_message" style="width:100%; height:100%; display:none; "> <h3>Error</h3> Sorry there was an error sending your form.</div>
</div>
</div>
</body>
<script>
$(document).ready(function() {
//this calculates values automatically
sum();
$("#nts, #pesta").on("keydown keyup", function() {
sum();
});
});
function sum() {
var nts = document.getElementById('nts').value;
var pesta = document.getElementById('pesta').value;
var refundTotal = parseInt(nts) + parseInt(pesta);
if (!isNaN(refundTotal)) {
document.getElementById('refund').value ="RM " + refundTotal;
}
}
function validateEmail($email) {
var re = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ($email == '' || !re.test($email))
{
return false;
}
}
function validateAlphabet($account_name){
var letters = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if($account_name.value.match(letters))
{
return true;
}
else
{
return false;
}
}
// function validateNumber (){
//
// }
function validateForm() {
$('#submit').disable=true;
var valid = true;
var error_msg="";
//school number
if($('#school_num').val()=='' && $.trim($('#school_num').val()).length<=0 ){
error_msg+=("Please insert your school number\n");
$('#school_num').addClass("error");
valid=false;
}else{
$('#school_num').removeClass("error");
}
//name
if($('#name').val()==''){
error_msg+=("Please insert your name\n");
$('#name').addClass("error");
valid=false;
}else{
$('#name').removeClass("error");
}
//email
if($('#email').val()==''){
error_msg+=("Please insert your email address\n");
$('#email').addClass("error");
valid=false;
}else{
if(validateEmail(document.getElementById('email').value)==false){
//console.log(document.getElementById('email').value);
error_msg+=("Invalid email address, Please fill in the correct email\n");
$('#email').addClass("error");
valid=false;
}else{
$('#email').removeClass("error");
}
}
//ic number
if($('#ic_num').val()==''){
error_msg+=("Please insert your IC Number (without dash)\n");
$('#ic_num').addClass("error");
valid=false;
}else{
if(!$.isNumeric($("#ic_num").val())){
//console.log(document.getElementById('email').value);
error_msg+=("Invalid IC Number - should be numbers only (no dash)\n");
$('#ic_number').addClass("error");
valid=false;
}else{
$('#ic_number').removeClass("error");
}
}
//school
if($('#school').val()=='-'){
error_msg+=("Please select your school\n");
$('#school').addClass("error");
valid=false;
}else{
$('#school').removeClass("error");
}
//nts
if($('#nts').val()=='-'){
error_msg+=("Please select your NTS refund amount\n");
$('#nts').addClass("error");
valid=false;
}else{
$('#nts').removeClass("error");
}
//pesta
if($('#pesta').val()=='-'){
error_msg+=("Please select your PESTA refund amount\n");
$('#pesta').addClass("error");
valid=false;
}else{
$('#pesta').removeClass("error");
}
if(error_msg!=""){
alert(error_msg);
}
if(valid){
$.ajax({
url: 'form_ajax.php',
type: 'POST',
data: {
'action':'check_duplicate',
'school_num':$('#school_num').val(),
'name':$('#name').val(),
'email':$('#email').val(),
'school':$('#school').val(),
'nts':$('#nts').val(),
'pesta':$('#pesta').val(),
'refund':$('#refund').val(),
},
error: function() {
},
before:function(){
},
dataType: 'json',
success: function(data) {
if(data.is_duplicated==0){
$.ajax({
url: 'form_ajax.php',
type: 'POST',
data: {
'action':'submit_form',
'school_num':$('#school_num').val(),
},
before:function(){
},
dataType: 'json',
success: function(data) {
$('#submit').disable=false;
if(data.status==1){
alert(data.message);
$('#success_message').show()
//TOOD: Clear all input
$('#school_num').val(''),
$('#name').val(''),
$('#email').val(''),
$('#school').val(''),
$('#nts').val(''),
$('#pesta').val(''),
$('#refund').val('')
}else{
alert(data.message);
$('#error_message').show()
}
},
error: function() {
},
});
//TOOD: Clear all input
$('#school_num').val(''),
$('#name').val(''),
$('#email').val(''),
$('#school').val(''),
$('#nts').val(''),
$('#pesta').val(''),
$('#refund').val('')
}
else{
alert('You already submit before');
}
},
});
}else{
$('#submit').disable=false;
}
}
</script>
</html>
My form_ajax.php file
<?php
//if(isset($_POST['submit'])){
if($_POST['action']=='submit_form'){
require "config.php";
require "common.php";
$statement=false;
$new_student = array(
"school_num" => $_POST['school_num'],
"name" => $_POST['name'],
"email" => $_POST['email'],
"ic_num" => $_POST['ic_num'],
"school" => $_POST['school'],
"nts" => $_POST['nts'],
"pesta" => $_POST['pesta'],
"remarks" => $_POST['remarks'],
"refund" => $_POST['refund']
);
try{
//#1 Open Connection
$connection = new PDO ($dsn,$username,$password,$options);
//#2 Prepare Sql QUERY
$statement = $connection->prepare("INSERT INTO details (school_num,name, email, ic_num,school,nts,pesta,remarks,refund,date) values (?,?,?,?,?,?,?,?,?,NOW())");
$statement ->bindParam(1,$_POST['school_num'],PDO::PARAM_STR);
$statement ->bindParam(2,$_POST['name'],PDO::PARAM_STR);
$statement ->bindParam(3,$_POST['email'],PDO::PARAM_STR);
$statement ->bindParam(4,str_replace($_POST['ic_num'], '-', ''),PDO::PARAM_INT);
$statement ->bindParam(5,$_POST['school'],PDO::PARAM_STR);;
$statement ->bindParam(6,$_POST['nts'],PDO::PARAM_INT);
$statement ->bindParam(7,$_POST['pesta'],PDO::PARAM_INT);
$statement ->bindParam(8,$_POST['remarks'],PDO::PARAM_STR);
$statement ->bindParam(9,$_POST['refund'],PDO::PARAM_INT);
//$statement = $connection->prepare($sql);
$statement->execute();
$return_message=array('status'=>1,'message'=>'Your information has been saved');
echo json_encode($return_message);
} catch (PDOException $error){
$return_message=array('status'=>0,'message'=>'Sorry we cannot save your information');
echo json_encode($return_message);
}
}
if( $_POST['action']=='check_duplicate'){
require "config.php";
require "common.php";
$statement=false;
try{
//#1 Open Connection
$connection = new PDO ($dsn,$username,$password,$options);
//#2 Prepare Sql QUERY
$statement = $connection->prepare("SELECT details.school_num FROM details");
$statement->bindParam(':school_num', $_POST ['school_num'], PDO::PARAM_STR);
//$statement = $connection->prepare($sql);
$statement->execute();
$statement->fetchAll();
$return_message=array('status'=>1,'message'=>'there is duplicate');
echo json_encode($return_message);
}catch (PDOException $error){
$return_message=array('status'=>0,'message'=>'no duplicate');
echo json_encode($return_message);
}
}
In your code php does not return the is_duplicated variable. Therefore, data.is_duplicated is always undefined in javascript. That's why result of if check if(data.is_duplicated==0) will always false, because undefined not equal to 0.
try to replace this code
$return_message=array('status'=>1,'message'=>'there is duplicate');
to this
$return_message=array('status'=>1,'message'=>'there is duplicate', 'is_duplicated' => 1);
and here
$return_message=array('status'=>0,'message'=>'no duplicate');
to this
$return_message=array('status'=>0,'message'=>'no duplicate', 'is_duplicated' => 0);
P.S.
By the way, why you don't check what statement has? I guess is not correct.
//$statement = $connection->prepare($sql);
$statement->execute();
$statement->fetchAll();
$return_message=array('status'=>1,'message'=>'there is duplicate');
echo json_encode($return_message);
should be
//$statement = $connection->prepare($sql);
$statement->execute();
$results = $statement->fetchAll();
if (empty($results)) {
$duplicate = 0;
} else {
$duplicate = 1;
}
$return_message=array('status'=>1,'message'=>'there is duplicate', 'is_duplicated' = $duplicate);
echo json_encode($return_message);
P.P.S.
To check if there is data in the database is better to use count() and limit=1
GOOD LUCK

Why isn't the file being read from being posted

I have code that is supposed to post a file to a php using js. It is not working. I have previously attempted to view the image that is being sent. This has not worked. Incase anyone wanted to view what the code does, this is a sample login: username:john & password:1234.If anyone could help me, thanks in advance.
This is the html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyCg8CauUyZeBGffR_2yAv7hkb-pD9zuzrA",
authDomain: "push-notifications-affa8.firebaseapp.com",
databaseURL: "https://push-notifications-affa8.firebaseio.com",
projectId: "push-notifications-affa8",
storageBucket: "push-notifications-affa8.appspot.com",
messagingSenderId: "1027448457059"
};
firebase.initializeApp(config);
</script>
<link rel="manifest" href="/manifest.json">
<title>MegaLords</title>
<link rel="stylesheet" href="styles/main.css">
<style>
#fileToUpload {
display:none;
}
#logout {
all: initial;
font-family: "Comic Sans MS", "Comic Sans", cursive;
cursor: pointer;
}
#logout:hover{
color: blue;
}
</style>
<script src="script/main.js"></script>
</head>
<body>
<div id="test" class = "topnav">
<a class=active>Home</a>
<a href=news.php>News</a>
<a href=contact.php>Contact</a>
<a href=about.php>About</a>
<a href=buy.php>Buy</a>
<?php
if(isset($_COOKIE['username'])){
echo "<a href=game.php>Play</a>";
echo "<button onclick=" . "document.getElementById('id04').style.display='block'" . ">Profile</button>";
}else{
echo "<button onclick=" . "document.getElementById('id01').style.display='block'" . ">Sign Up</button>";
echo "<button onclick=" . "document.getElementById('id02').style.display='block'" . "> Login</button>";
}
?>
</div>
<div id="id01" class="modal" style = 'padding-top: 50px;'>
<form id=signUpForm class="modal-content">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<p id ="errusra" class="err"></p>
<label><b>Username</b></label>
<input id="signUpUsername" type="text" placeholder="Enter Username" class = "profile" required>
<p id="erremaila" class="err"></p>
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" id="signUpEmail" class = "profile" required>
<p id="errpswa" class="err"></p>
<label><b>Password</b></label>
<input id="signUpPassword"type="password" placeholder="Enter Password" class = "profile" required>
<p id="errrepswa" class="err"></p>
<label><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" id="passwordRepeat" class = "profile" required>
<label>
<input type="checkbox" checked="checked" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelSignUpbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
<div id="id02" class="modal" style = "padding-top: 50px;">
<form id="loginform"class="modal-content animate">
<div class="imgcontainer">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal">×</span>
<img src="images/loginformimg.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<p id="loginerr" class = 'err'></p>
<label><b>Username</b></label>
<input id="loginUsername"type="text" placeholder="Enter Username" class="profile" required>
<label><b>Password</b></label>
<input id="loginPassword"type="password" placeholder="Enter Password" class = "profile" required>
<label>
<input type="checkbox" checked="checked" name = "cookies"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1; overflow:auto;">
<button type="submit"style="background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;">Login</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelLoginbtn loginButton">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<div id="id04" class="modal" style = "padding-top: 50px;">
<form id="changeInfoForm"class = "modal-content animate">
<div class="imgcontainer">
<?php
if(isset($_COOKIE['profilepic'])){
echo "<span onclick=" . '"document.getElementById(' . "'id04').style.display='none' " . '" class="close" title="Close Modal">×</span>
<label for="fileToUpload">
<img src="players/'. $_COOKIE['username']. '/' . $_COOKIE['profilepic'] . '" alt="Avatar" class="avatar" id="img">
</label>
<input type="file" name="fileToUpload" id="fileToUpload">';
}else{
echo "<span onclick=" . '"document.getElementById(' . "'id04').style.display='none' " . '" class="close" title="Close Modal">×</span>
<label for="fileToUpload">
<img src="images/loginformimg.png" alt="Avatar" class="avatar">
</label>
<input type="file" name="fileToUpload" id="fileToUpload">';
}
?>
</div>
<div class="container">
<label>
<b>Username:</b> <input id=changeusername class="profile" name="username"value = <?php echo $_COOKIE['username'];?>>
</label>
<br>
<label>
<b>Email:</b> <input id=changeemail class="profile" name="email"value = <?php if(isset($_COOKIE['email'])){ echo $_COOKIE['email']; } ?>>
</label>
<br>
<label>
<b>New Password:</b> <input id="changerepassword"type="password" name="password"class="profile" >
</label>
<br>
<label>
<b>Current Password:</b> <input id=changepassword type="password" name="new-password"class="profile" required>
</label>
<br>
</div>
<div class="container" style="background-color:#f1f1f1; overflow:auto;">
<input type="submit"style="background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;" value="Change Profile Info"name="submit">
<button type="button" onclick="document.getElementById('id04').style.display='none'" class="cancelLoginbtn loginButton">Cancel</button>
<span class="psw"><a id="logout"onclick="logout()">Logout</a></span>
</div>
</form>
</div>
<script src="profile.js"></script>
<?php include 'selectimage.php'?>
<h1>Welcome to MegaLords</h1>
<p>MegaLords is a place where mortals can become gods, and fallen gods can become true gods once more. Becoming a god is a very difficult process, and cannot be explained. Contact me if you wish to become a god.
<h4>Requirements</h4>
<ul>
<li>You must have beaten the game</li>
<li>You must be a mortal or fallen god</li>
<li>You must be weaker than a lower god</li>
<li>You cannot be a mythical creature, but we are looking for mythical creatures</li>
</ul>
<h4>Instructions</h4>
<ol>
<li>Beat the game</li>
<li>The Owner will immediately contact you, if not contact them</li>
<li>The Owner will grant you goddhood</li>
</ol>
</p>
<footer>
<p>Posted by: Electrox</p>
<p>Contact information: QuiMortemKing#gmail.com.</p>
</footer>
</body>
</html>
This is the website
https://omegalords.ga/
This is the js
if(window.location.href == "http://megalords.000webhostapp.com"){
window.location.href = "https://megalords.000webhostapp.com"
}else {
console.log(window.location.href)
}
// Get the modal
var modalLogin = document.getElementById('id02');
var modalSignUp = document.getElementById('id01');
var modalProfile = document.getElementById('id04');
var loginUsername = document.getElementById("loginUsername");
var loginPassword = document.getElementById("loginPassword");
var loginform = document.getElementById("loginform");
var signUpEmail = document.getElementById("signUpEmail");
var signUpUsername = document.getElementById("signUpUsername");
var signUpPassword = document.getElementById("signUpPassword");
var signUpRePassword = document.getElementById("passwordRepeat");
var signUpForm = document.getElementById("signUpForm");
var changeInfoUsername = document.getElementById("changeusername")
var changeInfoEmail = document.getElementById("changeemail")
var changeInfoPassword = document.getElementById("changepassword")
var changeInfoRePassword = document.getElementById("changerepassword")
var changeInfoForm = document.getElementById("changeInfoForm")
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modalLogin) {
modalLogin.style.display = "none";
}else if (event.target == modalSignUp) {
modalSignUp.style.dis4play = "none";
}else if (event.target == modalProfile){
modalProfile.style.display = "none";
}
}
var style = document.createElement('style');
var topnav = document.getElementsByClassName('topnav')[0];
var percent = 1/topnav.childElementCount * 100;
style.innerHTML += ".topnav a, button{float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; BORDER: none; width: " + percent + "%; }"
document.getElementsByTagName('head')[0].appendChild(style);
var getEmail = function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
if(this.responseText == "Please Refresh"){
location.reload();
}else {
return;
}
}else if(this.status == 404 || this.readyState === 0 || this.status == 404 && this.readyState === 0){
document.body.innerHTML = "File Not Found"
}
}
xhttp.open("GET", "getemail.php", true)
xhttp.send()
}
var getProfilepic = function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == "Please Refresh"){
location.reload();
}else if(this.responseText == "Your Account is Broken. The Dev Has Been Notified"){
document.body.innerHTML += this.responseText
}else if(this.responseText == "No Profile Picture Found"){
var confirmation = confirm("Would You like to Set a Profile picture?");
if(confirmation === true){
modalProfile.style.display = "block"
}
}
}
}
xhttp.open("GET", 'getprofileimage.php', true)
xhttp.send()
}
var signUp = function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == " Sign Up Complete"){
location.reload();
}else{
if(this.responseText == "No"){
document.getElementById("errusra").innerHTML = this.responseText;
}else{
switch(this.responseText){
case " *That Username Is Taken":
document.getElementById("errusra").innerHTML = this.responseText;
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You may only have letters and numbers as a username":
document.getElementById("errusra").innerHTML = this.responseText;
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You must have between 2 and 8 characters as username":
document.getElementById("errusra").innerHTML = this.responseText;
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *Invalid email":
document.getElementById("erremaila").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You must have at least one lowercase, uppercase, and a number as a password":
document.getElementById("errpswa").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You may only have between 3 and 12 characters as password":
document.getElementById("errpswa").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *Passwords do not match":
document.getElementById("errrepswa").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
break;
default:
document.body.innerHTML =this.responseText
console.log(this.responseText)
}
}
}
}
}
xhttp.open("GET",'checkregister.php?eml=' + signUpEmail.value + '&usrnm=' + signUpUsername.value + '&psw=' + signUpPassword.value + '&repsw='+ signUpRePassword.value,true);
xhttp.send();
}
var login = function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == "Login Successful!"){
location.reload();
}else{
modalLogin.style.display = "block";
console.log(this.responseText)
document.getElementById("loginerr").innerHTML = this.responseText;
}
}
}
xhttp.open("GET",'checklogin.php?usrnm=' + loginUsername.value + '&psw=' + loginPassword.value,true)
xhttp.send();
}
var logout = function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
location.reload();
}
}
xhttp.open("GET",'logout.php', true);
xhttp.send();
}
var changeInfo = function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
window.wormData = new FormData();
var file = document.getElementById("fileToUpload").files[0];
wormData.append('fileToUpload', file)
wormData.append('username',changeInfoUsername.value);
wormData.append('email',changeInfoEmail.value);
wormData.append('password',changeInfoPassword.value);
if(!(changeInfoRePassword.value == "")){
wormData.append('new-password',changeInfoRePassword.value)
}
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
console.log(this.responseText)
}
}
xhttp.open("POST","changeinfo.php",true);
xhttp.send(wormData);
}
signUpForm.addEventListener('submit',signUp);
loginform.addEventListener('submit',login);
changeInfoForm.addEventListener('submit',changeInfo);
getEmail();
getProfilepic();
This is the php
<?php
include 'templates/connect.php';
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST["new-password"])){
$newpassword = $_POST["new-password"];
}
$currusername = $_COOKIE['username'];
$query="SELECT * FROM `Users`
WHERE `username` = '$currusername' AND `psw` = '$password';";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$id = $row[0];
//echo $row[3];
if(!$result || mysqli_num_rows($result) === 0){
echo $username . $password;
}else{
if($row[1] === $username){
if($row[3] === $email || $email == ""){
if(isset($newpassword)){
$query="UPDATE `Users` SET `psw` = '$newpassword' WHERE `id` = '$id';";
echo $query;
$result = mysqli_query($conn, $query);
}else {
echo "Everything is the same";
}
}
}else if(isset($email)){
if(isset($newpassword)){
$query="UPDATE `Users` SET `username` = '$username' WHERE id = '$id';
UPDATE `Users` SET `password` = '$newpassword' WHERE `id` = '$id';";
rename('players/' . $row[1], 'players/' . $username);
$result = mysqli_query($conn, $query);
}
}else if(isset($newpassword)){
$query="UPDATE `Users` SET `username` = '$username' WHERE id = '$id';
UPDATE `Users` SET `email` = '$email' WHERE id = '$id';
UPDATE `Users` SET `password` = '$newpassword' WHERE `id` = '$id';";
$result = mysqli_query($conn, $query);
rename('players/' . $row[1], 'players/' . $username);
}else {
echo "Everything is the same";
}
}
foreach($_FILES as $data){
echo $data[name];
}
if(isset($_FILES['fileToUpload'])){
$target_dir = "players/". $_COOKIE['username'] . "/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(file_exists($_FILES['fileToUpload']['tmp_name']) || is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo basename( $_FILES["fileToUpload"]["name"]);
$query = "UPDATE `Users` SET `userimage` = '". $_FILES["fileToUpload"]["name"] . "' WHERE `username` = '$currusername'";
unlink("players/$row[1]/$row[5]");
$result = mysqli_query($conn, $query);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
}
?>
You have to set the enctype attribute in your form, so that the server can read the file.
<form id="changeInfoForm" class = "modal-content animate" enctype="multipart/form-data">

Upload audio using php which is recorded by jQuery plugin

I created a form where the visitor will submit some information. I used PHP to process the form and store data to MySql database.
Now I want to add a field where people can add their voice.
I used a jquery plugin to record the voice. The plugin records the voice and display in media player to play and provide a download option.
The link for the download is : blob:http://localhost/db0403fb-b131-4ebc-a421-86c5fb78137d
I want this audio to submit along with the form.
My code:
<?php
ob_start();
//RJ Application Form
//Connect Database
include('admin/connect.php');
//Set Variable
$name = $sex = $zone = $email = $mobile = $education = $why_to_be_rj = $file_name = "";
//Set Error array
$errors = array();
if (isset($_POST['submit']) && $_SERVER["REQUEST_METHOD"] == "POST") {
//Function to process data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//Check Name
if (empty($_POST["name"])) {
$errors['nameErr'] = 'Enter your name';
} else {
$name = test_input($_POST['name']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$errors['nameErr'] = 'Only letters and white space allowed';
}
}
//Check Sex
if ($_POST['sex'] == '1') {
$errors['sexErr'] = 'Select your sex';
} else {
$sex = $_POST['sex'];
}
//Check Audition Zone
if (empty($_POST["zone"])) {
$errors['$zoneErr'] = 'Enter your zone';
} else {
$zone = $_POST['zone'];
}
//Check Email
if (empty($_POST["email"])) {
$errors['emailErr'] = 'Enter your email';
} else {
$email = test_input($_POST['email']);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['emailErr'] = 'Invalid email format';
}
}
//Check Mobile
if (empty($_POST["mobile"])) {
$errors['mobileErr'] = 'Enter your mobile';
} else {
$mobile = test_input($_POST['mobile']);
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $mobile)) {
$errors['mobileErr'] = 'Only numbers are allowed';
}
}
//Check Education
if ($_POST["education"] == '1') {
$errors['educationErr'] = 'Select your education';
} else {
$education = $_POST['education'];
}
//Check Description
if (empty($_POST["about"])) {
//$why_to_be_rjErr = 'Enter why you want to be a RJ';
$errors['why_to_be_rjErr'] = 'Enter why you want to be a RJ';
} else {
$why_to_be_rj = test_input($_POST['about']);
}
//File Upload
if(!empty($_FILES['fileToUpload']['name']) && !empty($_FILES['fileToUpload']['tmp_name'])){
$uploadErr = array();
$target_dir = "uploads/";
//rename file before upload
$file_name = $name.$mobile.$_FILES["fileToUpload"]["name"];
$target_file = $target_dir . $name. $mobile. basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$audioFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Allow certain file formats
if($audioFileType != "AMR" &&
$audioFileType != "amr" &&
$audioFileType != "MP3" &&
$audioFileType != "mp3" &&
$audioFileType != "WAV" &&
$audioFileType != "wav" &&
$audioFileType != "AAC" &&
$audioFileType != "aac" ) {
//echo "Sorry, only AMR, MP3, WAV & AAC files are allowed.";
$uploadErr['fileErr'] = "Sorry, only AMR, MP3, WAV & AAC files are allowed.";
$uploadOk = 0;
}else{
// Check file size
if ($_FILES["fileToUpload"]["size"] > 100000000) {
echo "Sorry, your file is too large.";
$uploadErr['fileErr'] = "Sorry, your file is too large.";
$uploadOk = 0;
}else if(!$errors){
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
$file_upload_success = "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
$uploadErr['fileErr'] = "Sorry, there was an error uploading your file.";
}
}
}
}
// // Check if image file is a actual image or fake image
// $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
// if($check !== false) {
// echo "File is an image - " . $check["mime"] . ".";
// $uploadErr['fileErr'] = "File is an image - " . $check["mime"] . ".";
// $uploadOk = 1;
// } else {
// echo "File is not an image.";
// $uploadErr['fileErr'] = "File is not an image.";
// $uploadOk = 0;
// }
// // Check if file already exists
// if (file_exists($target_file)) {
// echo "Sorry, file already exists.";
// $uploadErr['fileErr'] = "Sorry, file already exists.";
// $uploadOk = 0;
// }
// // Check if $uploadOk is set to 0 by an error
// if ($uploadOk == 0) {
// echo "Sorry, your file was not uploaded.";
// $uploadErr['fileErr'] = "Sorry, your file was not uploaded.";
// // if everything is ok, try to upload file
// } else {
// if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
// $file_upload_success = "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
// } else {
// echo "Sorry, there was an error uploading your file.";
// $uploadErr['fileErr'] = "Sorry, there was an error uploading your file.";
// }
// }
if(!$errors){//Check if there is any errors. if no errors, then the data will be inserted into the database
//SQL to input data into rj-hunt table
$sql = "INSERT INTO `rj_hunt`(`name`, `sex`, `audition_zone`, `email`, `mobile`, `education`, `why_to_be_rj`, `voice`)
VALUES ('$name','$sex','$zone','$email','$mobile','$education','$why_to_be_rj','$file_name')";
//mysqli query. $conn is included at the begining of the script.
mysqli_query($conn, $sql);
//After iserting data successfully, redirect to a sub page to show success message.
header("location: rj-hunt.php?submit=success");
}//if no error, process done.
}//if clicked in submit button and method is post.
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="WebRTC getUserMedia MediaRecorder API">
<link rel="icon" href="img/ico.png">
<title>RJ HUNT</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
body { margin:0; padding:0; background: url(img/back.jpg); background-size:cover; position:relative; min-height:100vh; width:100%;}
.hunt-form{
margin-top: 20px;
}
.form-top{
background: #740808;
width: 31%;
margin: auto;
border-radius: 5px;
}
.form-top h2{
color: #ffc905;
padding: 10px 0;
font-family: Verdana;
}
form{
background: #740808;
padding: 20px 0 10px 10px;
border-radius: 10px;
border: 10px solid #97614B;
width: 80%;
margin: auto;
}
label{
color: #ffc905;
}
.error{
color: red;
}
.after-submit-message{
width: 50%;
margin: auto;
}
.after-submit-message h3{
background: yellowgreen;
color: #fff;
padding: 5px;
}
.btn-warning{
background: #EC971F;
}
button{
margin: 10px 5px;
}
li{
margin: 10px;
}
body{
width: 90%;
max-width: 960px;
margin: 0px auto;
}
#btns{
display: none;
}
h1{
margin: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="hunt-form">
<div class="form-top">
<h2 class="text-center"></h2>
</div>
<div class="after-submit-message">
<?php if(isset($_GET['submit']) && $_GET['submit']=='success'){echo '<h3 class="text-center">Your information submitted successfully</h3>';}?>
</div>
<form class="form-horizontal" method="post" action="" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-4 control-label" for="name">Name:</label>
<div class="col-sm-6">
<input class="form-control" value="<?php echo $name; ?>" type="text" name="name" id="name" placeholder="Name">
<span class="error"><?php if(isset($errors['nameErr'])){echo $errors['nameErr'];} ?></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="sex">Sex:</label>
<div class="col-sm-3">
<select class="form-control" name="sex" id="sex">
<option value="1">-- Select --</option>
<option value="Male" <?php if($sex == 'Male'){echo 'selected';}?>>Male</option>
<option value="Female" <?php if($sex == 'Female'){echo 'selected';}?>>Female</option>
</select>
<span class="error"><?php if(isset($errors['sexErr'])){echo $errors['sexErr'];} ?></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="zone">Audition Zone:</label>
<div class="col-sm-3">
<select class="form-control" name="zone" id="zone">
<option value="Dhaka">Dhaka</option>
</select>
<span class="error"><?php if(isset($errors['zoneErr'])){echo $errors['zoneErr'];} ?></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="email">Email:</label>
<div class="col-sm-6">
<input class="form-control" value="<?php echo $email; ?>" type="email" name="email" id="email" placeholder="Email">
<span class="error"><?php if(isset($errors['emailErr'])) {echo $errors['emailErr'];} ?></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="mobile">Mobile:</label>
<div class="col-sm-6">
<input class="form-control" value="<?php echo $mobile; ?>" type="tel" name="mobile" id="mobile" placeholder="Mobile">
<span class="error"><?php if(isset($errors['mobileErr'])) {echo $errors['mobileErr'];} ?></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="education">Education Level:</label>
<div class="col-sm-3">
<select class="form-control" name="education" id="education">
<option value="1">-- Select --</option>
<option value="Hsc" <?php if($education == 'Hsc'){echo 'selected';}?>>HSC</option>
<option value="Undergraduate" <?php if($education == 'Undergraduate'){echo 'selected';}?>>Undergraduate</option>
<option value="Ggraduate" <?php if($education == 'Ggraduate'){echo 'selected';}?>>Graduate</option>
</select>
<span class="error"><?php if(isset($errors['educationErr'])) {echo $errors['educationErr'];} ?></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="about">Why you want to be a RJ:<br/>(300 words)</label>
<div class="col-sm-6">
<textarea class="form-control" name="about" id="about" rows="4" placeholder="Why you want to be a RJ? (300 words)"><?php echo $why_to_be_rj; ?></textarea>
<span class="error"><?php if(isset($errors['why_to_be_rjErr'])) {echo $errors['why_to_be_rjErr'];} ?></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="fileToUpload">Add Voice</label>
<div class="col-sm-4">
<input class="form-control" value="<?php echo $file_name;?>" type="file" name="fileToUpload" id="fileToUpload">
<span class="error"><?php if(isset($uploadErr['fileErr'])) {echo $uploadErr['fileErr'];} ?></span>
</div>
</div>
<div form-group>
<label class="col-sm-4 control-label" id='mediaAudio'>Record Voice</label>
<div class="col-sm-4">
<div id='gUMArea'>
<input class="btn btn-default" id='gUMbtn' value="Use Microphone">
</div>
<div id='btns'>
<button class="btn btn-default" id='start'>Start</button>
<button class="btn btn-default" id='stop'>Stop</button>
</div>
<div>
<ul class="list-unstyled" id='ul'></ul>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-sm-offset-4">
<input class="btn btn-warning btn-lg" type="submit" name="submit" id="submit" value="Submit">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>-->
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="js/media-recorder.js"></script>
</body>
</html>
<?php ob_end_flush();?>

Codeigniter: login as admin user and login as employee user

Hi I'm currently working on codeigniter framework and I'm currently working on a project which is basically an admin/employee login system.
Currently I have been able to create a login form, and can successfully get a user to login, after having checked the user exists.
I just wanted to be pointed in the right direction as to how I could go about this to be able to login an employee user to an employees page, and an admin user to an admin page.
This is what I have at the moment, which is fully functioning using bootstrap as a front end framework. But allows any user to login.
By the way I have only one table name "employees" which consist only for employee user and admin user from mysql database.
Here is the view: (login.php)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=1,initial-scale=1,user-scalable=1" />
<title> Login Form </title>
<link href="http://fonts.googleapis.com/css?family=Lato:100italic,100,300italic,300,400italic,400,700italic,700,900italic,900" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/styles.css" />
<script src="<?php echo base_url()?>assets/js/bootstrap.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<script>
$(document).ready(function () {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
switch (e.srcElement.id) {
case "username":
e.target.setCustomValidity("Username cannot be blank");
break;
case "pass":
e.target.setCustomValidity("Password cannot be blank");
break;
}
}
};
elements[i].oninput = function (e) {
e.target.setCustomValidity("");
};
}
})
</script>
<style type="text/css">
.back{
position: absolute;
bottom: 0px;
left: 0px;
}
</style>
<section class="container">
<section class="login-form">
<form class="form-signin" action="goClock" method="post" role="login">
<img src="<?php echo base_url()?>assets/images/easypay.png" class="img-responsive center-block" alt="" />
<input type="text" class="form-control input-lg" placeholder="username" name='user' required id="username" autocomplete="off" autofocus />
<input type="password" class="form-control input-lg" placeholder="Password" name='password' required id="pass" required />
<?php
if(!empty($login_error)) {
echo $login_error;
}
?>
<button name='login' class="btn btn-lg btn-block btn-primary" value=" LOGIN " type="submit" id="button2">Login</button>
</form>
<p class="text-center" style="font-weight: bold; font-size: 60;" id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</section>
</section>
<div class="back">
<input class="btn btn-warning" action="action" type="button" value="<- Back" onclick="location.href = 'index';" />
</div>
</body>
</html>
Here is the controller: (home.php)
public function goClock($message = null) {
$this->load->view('imports/header');
$this->load->view('imports/menu');
if (!is_null($this->input->post('login'))) {
$username = $this->input->post('user');
$password = $this->input->post('password');
$userdata = $this->model_home->get_userinfo($username, $password);
$_SESSION['is_loggedin'] = true;
if ($userdata !== false) {
$this->session->set_userdata($userdata);
redirect('home/goHome');
}else {
$data['login_error'] = '<p style="font-size: 16px; color: red;" align="center">Invalid Username or Password</p>';
$this->load->view('login', $data);
}
}else {
$data['username'] = $this->input->post('user');
$data['password'] = $this->input->post('password');
$this->load->view('clock', $data);
}
}
And finally here is the model: (model_home.php)
public function get_userinfo($username = null, $password = null) {
if ($username && $password) {
$this->db->select('username, password, empnum');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('employees');
if ($query->num_rows()) {
return $query->result_array()[0];
}
}
return false;
}
Just to clarify I have only one controller, my main controller by default which is home.php. In conclusion my aim is to be able to redirect an admin user to admin.php and to be able to redirect a employee user to employee.php (Hasn't been created yet).
P.S I already have a column in my table in PhpMyAdmin called "employees".
Please help me. Thank you in advance.
you should add one extra column in Database named as user_type and Set default value=0 for that and for "admin" set it 1.
Now modify your query like this:
if ($username && $password) {
$this->db->select('username, password, empnum,user_type');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('employees');
if ($query->num_rows()) {
return $query->result_array()[0];
}
}
Now check the $userdata[] array value having user_type key if it is 1 then
$this->load->view('admin', $data);
else he is user_type = 0 which means employee
$this->load->view('employee', $data);
NOTE:I can provide the way but here you have to modify your array key and view name as per the need.
First create a filed with name usertype in your database employees table.
Run this query in your phpMyadmin database
ALTER TABLE `employees` ADD `usertype` ENUM('user','employee') NOT NULL DEFAULT 'user' ;
and add following code on your Model
public function get_userinfo($username = null, $password = null) {
if ($username && $password) {
$this->db->select('username, password, empnum,usertype');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('employees');
if ($query->num_rows()) {
return $query->row();
}
}
return false;
}
And on your controller
public function goClock($message = null) {
$this->load->view('imports/header');
$this->load->view('imports/menu');
if (!is_null($this->input->post('login'))) {
$username = $this->input->post('user');
$password = $this->input->post('password');
$userdata = $this->model_home->get_userinfo($username, $password);
$_SESSION['is_loggedin'] = true;
if ($userdata !== false) {
if($userdata->usertype=='user'){ # if user then redirect to user page
redirect('home/goHome');
}else{
# If employee redirect to admin page
}
}else {
$data['login_error'] = '<p style="font-size: 16px; color: red;" align="center">Invalid Username or Password</p>';
$this->load->view('login', $data);
}
}else {
$data['username'] = $this->input->post('user');
$data['password'] = $this->input->post('password');
$this->load->view('clock', $data);
}
}

Javascript White Space Passed Through Form

I have a sign up form that uses AJAX to pass the data to a PHP script and enter it into a MySQL database.
However, the issue I am having is that when someone enters a username like so this:
"Username Test" the space isn't parsed properly, so when you go to view the profile of that user via a link it won't work.
So my question is how to parse a space within Javascript and PHP if you know as well but I'm pretty sure the PHP side of things is good.
Firebug outputs this when the form is submitted:
Parameters application/x-www-form-urlencoded
emailSignUp nickdimartino91#gmail.com
passwordSignUp nidima10
usernameSignUp Username Test
Source
usernameSignUp=Username+Test&passwordSignUp=nidima10&emailSignUp=nickdimartino91%40gmail.com
I echo'd the value of the username field within the PHP script and it returns with a space in the username. Yet it's not getting entered that way into the DB. What is the issue?
UPDATE: Not sure what I did but all is working now!
Sign up form:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" id="signUpForm" method="post" name="signUpForm">
<input class="formInput" id="usernameSignUp" name="usernameSignUp" placeholder="Username" required="required" type="text" style="margin-right: 6px;">
<input class="formInput" id="passwordSignUp" name="passwordSignUp" placeholder="Password" required="required" type="password" /><br>
<input class="formInput" id="emailSignUp" name="emailSignUp" placeholder="Email" required="required" type="email" style="margin-bottom: 10px; margin-top: 10px; width: 326px;"><br>
<input class="formButton" id="signUpSubmit" name="signUpSubmit" type="submit" value="Sign Up">
<div id="signUpLoading" style="display: none; height: auto; margin-top: 10px; width: auto;"><img alt="Loading" src="/images/loading.gif"><span class="loadingMessage">Signing up...</span></div>
<div id="signUpResponse" style="display: none; height: auto; margin-top: 10px; width: auto;"></div>
</form>
JS bit that does the AJAX stuff:
<script>
$(document).ready(function() {
$("#signUpForm").submit(function() {
$(document).ajaxStart(function() {
$("#signUpLoading" ).show();
});
$.ajax({
url:"/ajax/signUp.php", // Action of the form
data:$("#signUpForm").serialize(), // Send forms data to server
dataType:"JSON", // Take response as JSON
type:"POST", // Send form by post or get
complete:function(result) {
$(document).ajaxStop(function() {
$("#signUpLoading" ).hide();
});
$("#signUpResponse").html(result.responseText);
$("#signUpResponse").slideDown("slow");
}
});
return false; // Default submit return false
});
});
</script>
signUp.php
<?php
require('../core/core.php');
if (!empty($_POST)) {
$username = $_POST['usernameSignUp'];
$password = $_POST['passwordSignUp'];
$email = strtolower($_POST['emailSignUp']);
if (empty($username)) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Please enter a username.</span>';
}
elseif (empty($password)) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Please enter a password.</span>';
}
elseif (empty($email)) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Please enter your email address.</span>';
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Please enter a valid email address.</span>';
}
elseif (strlen($username) < 2 || strlen($username) > 32) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Your username must be between 2 and 32 characters long.</span>';
}
elseif (strlen($password) < 6 || strlen($password) > 32) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">Your password must be between 6 and 32 characters long.</span>';
}
elseif ($users->userExists($username) === true) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">The username you\'ve entered is unavailable.</span>';
}
elseif ($users->emailExists($email) === true) {
$errors[] = '<img alt="Error" src="/images/error.png"><span class="errorMessage">The email you\'ve entered is already associated with another account.</span>';
}
else {
$hashedPassword = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$users->signUp($username, $hashedPassword, $email);
echo '<img alt="Success" src="/images/success.png"><span class="successMessage">Thanks for joining the LiveGrooves Community!<br>We\'ve sent you an email with your account information, an activation link, and some tips on getting started.</span>';
return true;
}
}
if (!empty($errors)) {
echo '<p>' . implode('</p><p>', $errors) . '</p>';
}
?>

Categories