same data inserting twice in xampp mysql - php

I am using PHP 5.6.30 version..when I try to execute the following code data is inserted twice.i am using register.php as view and app.js for http post service.
insert.php (database connection)
<?php
$connect = mysqli_connect("localhost", "root", "","user");
$data = json_decode(file_get_contents("php://input"));
$first_name = mysqli_real_escape_string($connect, $data->firstname);
$last_name = mysqli_real_escape_string($connect, $data->lastname);
$user_name = mysqli_real_escape_string($connect, $data->username);
$emailid = mysqli_real_escape_string($connect,$data->emailid);
$password = mysqli_real_escape_string($connect,$data->password);
$mobile = mysqli_real_escape_string($connect,$data->mobile);
$query = "INSERT INTO register(fname,lname,uname,email,pass,mobile)
VALUES ('$first_name','$last_name','$user_name','$emailid','$password','$mobile')";
$result = mysqli_query($connect, $query) ;
if($result == TRUE)
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
?>
register.php:
enter code here
<html>
<head><title>Nav</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-
route.js"></script>
<link rel="stylesheet" type="text/css" href="css/header.css"/>
<script src="app.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="RegisterController">
<form ng-submit="rsubmit()" class="rform">REGISTER
<input type="text" class="form-control" name="firstname" ng-
model="firstname" placeholder="firstnamesss" ><br>
<input type="text" class="form-control" name="lastname" ng-
model="lastname" placeholder="lastname" ><br>
<input type="text" class="form-control" name="username" ng-model="username" placeholder="username"><br>
<input type="text" class="form-control" name="emailid" ng-model="emailid" placeholder="emailid" ><br>
<input type="text" class="form-control" name="password" ng-model="password" placeholder="password" required=""/><br>
<input type="text" class="form-control" name="mobile" ng-model="mobile" placeholder="mobileno" ><br>
<button ng-click="rsubmit()" >Register</button>
Cancel
<br></h2>
</form>
</div>
</body>
</html>
app.js:
var app = angular.module('myApp', ['ngRoute']);
app.controller('RegisterController',function($scope,$http){
$scope.rsubmit=function(){
$http.post("insert.php" ,{
'firstname':$scope.firstname,
'lastname':$scope.lastname,
'username':$scope.username,
'emailid':$scope.emailid,
'password':$scope.password,
'mobile':$scope.mobile,
} )
.success(function(data){
alert(data);
$scope.firstname = null;
// $scope.lastname = null;
});
}
});

From the documentation:
Warning: Be careful not to cause "double-submission" by using both the ngClick and ngSubmit handlers together. See the form directive documentation for a detailed discussion of when ngSubmit may be triggered.
In your code you use both ng-submit and ng-click, so you trigger the controller (the request) twice. Just remove the ngClick attribute on the button/ input field and it should work.

Just remove the ng-click from the button..Button used inside the form always submit the form..So you call the rsubmit function when click the button at same time when you click the button the form is going to submission.The form submission call again the rsubmit function..
Two types of ways for it
1.<button type="button" ng-click="rsubmit()" >Register</button> - It disable the form submission power of button when you use type="button"
(or)
2.Skip the action attribute from the form.

Related

Login system with Client Hash

I am trying to make a simple login system that allows users to register/login, but want to hash the password on the client side before sending it over to the server. I know this isn't standard practice but trying to get it to work. Was hoping I could get some insight of where I am going wrong.
Here is my code so far:
<?php
include_once('connect.php');
$username = $_POST['username'];
$sql = "SELECT salt FROM users WHERE username = '$username';";
$result = $conn->query($sql);
$row = mysqli_fetch_assoc($result);
echo $row['salt'];
$variable = $_GET['tmp'];
$getPass = "SELECT passwordhash FROM users WHERE username = '$username' AND passwordhash = '$variable ';";
//Run the sql and either set tmp variable of isValid to 1 or 0 and then echo it below or see how many rows are returned?
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="sha256.js"> </script>
<script>
function changeFormLogin() {
var pass = document.getElementById('getPass').value;
var username = document.getElementById('username').value;
var getSalt = <?php echo $row['salt']; ?>
var hashpass = SHA256(pass+pass);
var tmp = validateLogin(hashpass);
if(tmp ==1){
//Welcome the user back, and load new form
}
else{
//Tell them to try again, notify them.
}
document.getElementById("demo").innerHTML = getSalt; //Used for testing
return true;
}
function validateLogin(hashPass){
}
</script>
</head>
<body>
<div class="loginBox">
<img src="user.png" class="user">
<h2>Log In Here</h2>
<form action="#" onsubmit ="return changeFormLogin()">
<p>Email</p>
<input id="username" type="email" name="username" placeholder="Enter Email" required>
<p>Password</p>
<input id="getPass" type="password" name="password" placeholder="••••••" required>
<input type="submit" name="login" value="Sign In">
<p id="demo"></p>
</form>
<input type="submit" name="login" value="Return home">
</div>
Or if there is a way to simplify this I am all for it!
You are allowing form to submit to server and it prevents javascript to execute.
I'm not sure if You are using https://cdnjs.com/libraries/js-sha256 library or similar to it but, It needs sha256 in lowercase instead of uppercase like you have typed.
Here is the working code,
function changeFormLogin() {
var pass = document.getElementById('getPass').value;
var username = document.getElementById('username').value;
var getSalt = 123566 //your salt
var hashpass = sha256(pass+pass);
console.log(hashpass);
var tmp = validateLogin(hashpass);
if(tmp ==1){
//Welcome the user back, and load new form
}
else{
//Tell them to try again, notify them.
}
document.getElementById("demo").innerHTML = getSalt; //Used for testing
return true;
}
function validateLogin(hashPass){
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js" ></script>
</head>
<body>
<div class="loginBox">
<img src="user.png" class="user">
<h2>Log In Here</h2>
<form action="javascript:;" onsubmit="return changeFormLogin()">
<p>Email</p>
<input id="username" type="email" name="username" placeholder="Enter Email" required>
<p>Password</p>
<input id="getPass" type="password" name="password" placeholder="••••••" required>
<input type="submit" name="login" value="Sign In">
<p id="demo"></p>
</form>
<input type="submit" name="login" value="Return home">
</div>
</body>
</html>
Something which you can do , Doesn't mean you should do, You are using GET to get the hashed string which is bad practice. Also you should never do operations on client side which should be done at server side, such as hashing the passwords.
NEVER use anything like this for production purpose and like others said in comments, Please have a look what SQL injection is and never trust what your user types in input fields.

Displaying differnt border color if field is valid

So I have my form which I have supplied pictures of below. The left side picture is a normal border color but then the red outline on the right is when the form input is invalid.
How would I do this through PHP? Here's the corresponding code
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
exit($e->getMessage());
}
// Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
// Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)) {
echo "Complete all fields";
}
// Password match
if ($password != $password1) {
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
And my HTML form
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
So if the input satisfies the if statement how would I display the color?
When your form has errors, you need to re-display it. It's hard to give a recommendation without knowing your code structure, but I will assume that your HTML is rendered via a call to php. Generally, I have done something like
$error = false
//this $_GET['submit'] variable could be part of the URL of your submitted form.
//alternately, you could check the HTTP method of the page request
if ($_GET['submit']) {
//run your form logic
//if you have success, run your php query and then redirect
//to your "success" page using a 302 (using a header("Location:... sort of call)
//you would also want to call die() or something right here
}
//if you make it this far, display your page including the bits about errors
//your form's action goes right back to the same page that rendered it, but with
//some change to the url to let the script know that you want to process the form
With PHP5 and with warnings about undefined variables turned on, you would need to define all of your error message variables before checking whether or not the form is being submitted.
Asuming you are using twitter bootstrap since you have form-control all over the place, (assuming >= 3.0.0), you can use (for the graphical side of things) has-suceess, has-error, etc like shown here: http://getbootstrap.com/css/#forms-control-validation.
When you re-display the form due to bad data, pass along your error messages to whatever renders your html. An example with your thing would be (assuming your form has access to $passmatch, $emailvalid,$passlength):
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
</div>
<div class="form-group <?php if (!empty($emailvalid)) { echo 'has-error'; } ?>">
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
</div>
<div class="form-group <?php if (!empty($passmatch) || !empty($passlength)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group <?php if (!empty($passmatch)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
I would recommend using a templating engine or something to separate the view from the actual code.
As for the help text, you can use something like this after the elements with errors:
<div class="form-group <?php if (!empty($yourVariable)) { echo 'has-error'; }?>">
<input type="text" class="form-control" />
<span class="help-block"><?php echo $yourVariable; ?></span>
</div>
The fun part is, if you have no error message, the help block won't even be shown because that variable won't have anything in it.
EDIT
Example page: http://content.kevincuzner.com/register.php
Example source: https://gist.github.com/kcuzner/11323907
I would handle this on the client side with JavaScript. On submission of the form, you can check whether the input is valid or not and then just update the border color using JavaScript.
The <?php ?> you can fill in above (if you want to go this route) can just depend on some variable that checks validity:
echo "Complete all fields";
$fieldsValid = false;
border-color: <?php $fieldsValid ? 'blue' : 'red' ?>
But you need to do a full page reload for this to work. JavaScript is a better route:
document.forms[0].addEventListener("submit", function () {
var usernameInput = document.querySelector("[name=username]");
if (!usernameInput.value) {
usernameInput.style.borderColor = "red";
}
});

Webservices in PHP and Oracle Database

i want to create a web service to check if the login
i create first an html form
<form action="webservice_ocl.php" method="post">
<p>Username:
<input name="user" type="text" />
</p>
<p>
Password:
<input name="password" type="password" />
</p>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</p>
</form>
then i create a php file " webservice_ocl.php to do the traitement
<?php
session_start();
try {
$dbh = oci_connect('test', '123456', 'localhost/XE');
} catch (PDOException $e)
{
echo $e->getMessage();
}
if ($_POST['user'] != null and $_POST['user'] != "" and $_POST['password'] != null and $_POST['password'] != "")
{
$username = $_POST['user'];
$password = $_POST['password'];
$sth = oci_parse($dbh ,"SELECT * FROM utilisateur WHERE LOGIN='$username' and PASS='$password'");
oci_execute($sth);
if(oci_fetch($sth)){
echo "Nice";
}
else { echo "nono";}
}
?>
i want to konw , the php file " webservice_ocl.php " is a webservice ??
and how to call them in html using ajax ??
i want to use this on mobile developpement
I wouldn't really class webservice_ocl.php as a webservice as such, a webservice (in my opinion) is usually an SOAP/REST complaint API. See http://en.wikipedia.org/wiki/Web_service.
As for calling this with AJAX, I would personally look into jquery - namely the $.post function, I use this all the time and find it much easier than plain javascript.
Lastly, i would advise you look at how you have wrote your SQL statements - as pointed out by Quentin you are vulnerable for injection, which I have had done before (whoops) and believe me it is not nice!
Hope this helps.
Smithey.
Edit - If your looking at mobile apps, take a look at jquery mobile ;). I'm using it for a project im working on at the minute, its pretty cool!
====== in form.html change type="submit" to type="button" and delete action+mithod attr
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<form id="my-form" >
<p>Username:
<input name="user" type="text" />
</p>
<p>
Password:
<input name="password" type="password" />
</p>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</p>
</form>
<div id=result >the result will display here</div>
<script type="text/javascript">
$("#btnSubmit").click({
$.post(
"webservice_ocl.php",
$("#my-form").serialize(),
function(data){ $("#result").html(data); }
);
});
</script>

PHP form validation, uses Javascript for error messages

OK so I have an email form on index.php. I am using mail_check.php to validate that both fields are filled in.
(there are more that is being validated, but not included as it is not the issue)
The main issue is that from the mail_check.php I want to be sent back to the index.php with a message in placed in the div id="mailrespond". I have chosen both PHP and Javascript to achieve this.
Index.php
<div id="mailrespond"></div>
<form method="post" action="mail_check.php">
<span>Name: <input type="text" name="name" maxlength="30" /></span><br />
<span>Email: <input type="text" name="email" maxlength="30" /></span><br />
<input type="submit" value="Sign Up" name="registration">
</form>
</div>
mail_check.php
if(isset($_POST['registration']))
$name = $_POST['name'];
$email = $_POST['email'];
if(empty($email) || empty($name)){
// if email and name are empty
//header ("location: index.php");
?>
<script language="javascript" type="text/javascript">
window.location.replace("index.php");
function msg() {
// creating elements are a safer method then innerHTML
dv = document.createElement('div'); // creates a Div element
dv.setAttribute('class', 'error_msg'); // adds error styling
txt = document.createTextNode('please enter your name and email '); // create the message
dv.appendChild(txt); // place the text node on the element
document.getElementById("mailrespond").appendChild(dv);
}
window.onload = msg;
</script>
<?php }
The code goes on, but My issue is that I am not getting the feed back messages. I am a little new to this all - if you can help that would be much appreciated! :)
<---- #downvoter please leave a reason! Thanks
Try this (and don't call a form field name, please since a form can have a name too)
Index.php
<!DOCTYPE html>
<html>
<head>
<title>Mail respond</title>
<script>
window.onload=function() {
document.getElementById("mailform").onsubmit=function(){
if (this.fullname.value=="" || this.email.value=="") {
alert("Please fill in name and email");
return false;
}
return true; // allow form submission
}
}
</script>
</head>
<body>
<div id="mailrespond"></div>
<form method="post" action="mail_check.php" id="mailform">
<span>Name: <input type="text" name="fullname" maxlength="30" /></span><br />
<span>Email: <input type="text" name="email" maxlength="30" /></span><br />
<input type="submit" value="Sign Up" name="registration">
</form>
</div>
</body>
</html>
mail_check.php
<?PHP
if(isset($_POST['registration']))
$name = $_POST['fullname'];
$email = $_POST['email'];
if(empty($email) || empty($name)){
// if email and name are empty - only seen if JavaScript is turned off
?>
<h3>You did not fill in name and email</h3>
<p>please wait to be redirected or click <a href='index.php'>here</a></p>;
<meta http-equiv="refresh" content="3; url=http://example.com/index.php" />
<script type="text/javascript">
window.onload=function() {
setTimeout(function() {
window.location.replace("index.php");
},3000);
}
</script>
<?php } ?>
You're redirecting to index.php in the msg function, so it does nothing else.
You should do it by pure PHP, set a component in $_SESSION, redirect by PHP to index.php and in the index.php check if the component exists.

Execute PHP without being redirected to the action linked file?

If I have a submit button that will execute a PHP script, can I execute it without actually going to that page, i.e.: process.php? I'm used to JavaScript being able to do this.
(For the record, I'm talking about without AJAX, without redirecting once on that other page, and no, I'm not very hopeful.)
The reason you are able to do this with JavaScript is because JavaScript can execute within the browser on the client side. PHP on the other hand ALWAYS executes on the server and returns HTML to the client.In short, no you can't.
One way to do it without AJAX is to submit the form to an invisible iframe, like so:
<form action="blah.php" target="theReallyCoolIframe">...</form>
<iframe name="theReallyCoolIframe></iframe>
Note that this isn't really a very graceful solution; AJAX is a much better solution overall, and isn't that difficult - you should look in to jQuery and its AJAX APIs.
Try this, if you want to use a PHP only solution to your problem.
<?php
function submit_form(){
$host = "localhost";
$user = "user";
$password = "password";
$database = "database";
$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
$lastname = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
$email = filter_var(filter_var($_POST['email'],FILTER_SANITIZE_EMAIL),FILTER_VALIDATE_EMAIL);
// open connection to database
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
//INSERT VALUES INTO DATABASE
$query = "INSERT INTO users (firstname,lastname,email)
VALUES('".$firstname."', '".$lastname."', '".$email."'";
return mysqli_query($link,$query);
}
//close connection to database
mysqli_close($link);
}
$form = <<<EODuserform
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Form</title>
</head>
<form action="{$_SERVER['PHP_SELF']}" method="POST" name="userform">
<label for='first'>First Name:</label></br>
<input type="text" name="firstname" id="first" maxlength="25" tabindex='1' VALUE="firstname" /></br>
<label for='first'>Last Name:</label></br>
<input type="text" name="lastname" id='lastname' maxlength="25" tabindex='2' VALUE="lastname" /></br>
<label for='email'>E-mail:</label></br>
<input type="text" name="email" id='email' maxlength="100" tabindex='3' VALUE="email" /></br>
<input type="submit" class='button' name="submit" value="submit" tabindex='4' />
</form>
</body>
</html>
EODuserform;
IF(!IsSet($_POST['submit'])){ // Check if form is not send, if not display empty form.
echo $form;
}
ELSE{
// in the case you want to send something to the database use
submit_form();
echo ('Thanks for submitting your form');
}
?>
It is a very basic script you can find a similar script on this page: Form not saving to database

Categories