I am made a form validation using PHP. If the error happens, the error msg will show around each input column. I would like to check if the email is used or not. So, I used error code to define if input email addr is used, then showing the error message for "The email has been used". However, the result becomes whatever I input, it only shows "The email has been used". Could some help me for this issue? Thanks!
<?php
require_once('./conn.php');
$errorMsgs = array('nickname'=>'', 'email'=>'', 'password'=>'');
if(isset($_POST['submit'])) {
if(empty($_POST['nickname'])) {
$errorMsgs['nickname'] = "Please enter your nickname";
}
$email = $_POST['email'];
$password = $_POST['password'];
// checking the email is valid or empty
if(empty($_POST['email'])) {
$errorMsgs['email'] = "Please enter your email";
} else {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMsgs['email'] = "Please enter a valid email";
}
}
$errorCode = $conn->errno;
if($errorCode === 1062) {
$errorMsgs['email'] = "The email has been used";
}
// checking the password is valid or empty
if(empty($_POST['password'])) {
$errorMsgs['password'] = "Please enter your password";
} else {
if(!preg_match('/\w{8,}/', $password)) {
$errorMsgs['password'] = "Please enter at least 8 characters";
}
}
if(!array_filter($errorMsgs)) {
$sql = sprintf("INSERT INTO member (nickname, email, password) values ('%s', '%s', '%s')", $_POST['nickname'], $_POST['email'],$_POST['password']);
$result = $conn->query($sql);
if($result) {
header("Location: index.php");
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" />
<title>Message Board - Sign Up</title>
</head>
<body>
<div class="container__signup">
<h1 class="title">Create Account</h1>
<form class="signup" method="POST" action="signup.php">
<div>
<i class="far fa-user"></i>
<input type="text" placeholder="Name" name="nickname">
</div>
<p class="warning__msg"><?php echo $errorMsgs['nickname'];?></p>
<div>
<i class="far fa-envelope"></i>
<input type="text" placeholder="Email" name="email">
</div>
<p class="warning__msg"><?php echo $errorMsgs['email'];?></p>
<div>
<i class="fas fa-lock"></i>
<input type="password" placeholder="Password" name="password">
</div>
<p class="warning__msg"><?php echo $errorMsgs['password'];?></p>
<input type="submit" value="SIGN UP" name="submit">
</form>
</div>
</body>
</html>
You have to check if the email exists in your user table.
something like this.
<?php
require_once('./conn.php');
$errorMsgs = array('nickname'=>'', 'email'=>'', 'password'=>'');
if(isset($_POST['submit'])) {
if(empty($_POST['nickname'])) {
$errorMsgs['nickname'] = "Please enter your nickname";
}
$email = $_POST['email'];
$password = $_POST['password'];
// checking the email is valid or empty
if(empty($_POST['email'])) {
$errorMsgs['email'] = "Please enter your email";
} else {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMsgs['email'] = "Please enter a valid email";
}
else{
//you should use sql parameter binding
$email = $_POST['email'];
$checkDuplicate= $conn->query("SELECT email FROM user_table where email = '$email'");
if(!empty($checkDuplicate)) {
$errorMsgs['email'] = "The email has been used";
}
}
}
// checking the password is valid or empty
if(empty($_POST['password'])) {
$errorMsgs['password'] = "Please enter your password";
} else {
if(!preg_match('/\w{8,}/', $password)) {
$errorMsgs['password'] = "Please enter at least 8 characters";
}
}
if(empty($errorMsgs)) { //you need to check if there's any error
$sql = sprintf("INSERT INTO member (nickname, email, password) values ('%s', '%s', '%s')", $_POST['nickname'], $_POST['email'],$_POST['password']);
$result = $conn->query($sql);
if($result) {
header("Location: index.php");
}
}
}
?>
Related
This is jslogin.php
<?php
error_reporting(-1);
session_start();
require_once('config.php');
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$isValid = true;
if (empty($password)) {
echo 'You need to enter a Password';
$isValid = false;
}
if (empty($username)) {
echo 'You need to enter a Username';
$isValid = false;
}
if (empty($email)) {
echo 'You need to enter a Email Address';
$isValid = false;
}elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "You need to have a valid Email Address";
$isValid = false;
}
if ($isValid) {
$sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
$stmtselect = $db->prepare($sql);
$result = $stmtselect->execute([$username, $password, $email]);
$user = $stmtselect->fetch(PDO::FETCH_ASSOC);
if ($stmtselect->rowCount() > 0) {
$_SESSION['accounts'] = $user;
echo 'You have signed in successfully!';
} else {
echo 'Incorrect Username or Password or Email';
}
}
This is login.php
<?php
error_reporting(-1);
session_start();
if(isset($_SESSION['hello_world_accounts'])){
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Programming Knowledge Login</title>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="container h-100">
<div class="d-flex justify-content-center h-100">
<div class="user_card">
<div class="d-flex justify-content-center">
<div class="brand_logo_container">
<img src="img/logo.png" class="brand_logo" alt="Programming Knowledge logo">
</div>
</div>
<div class="d-flex justify-content-center form_container">
<form method="post">
<div class="input-group mb-2">
<div class="input-group-append">
<span class="input-group-text"><em class="fas fa-user"></em></span>
</div>
<input type="text" name="username" id="username" class="form-control input_user" placeholder="Username" required>
</div>
<div class="input-group mb-2">
<div class="input-group-append">
<span class="input-group-text"><em class="fas fa-key"></em></span>
</div>
<input type="password" name="password" id="password" class="form-control input_pass" placeholder="Password" required>
</div>
<div class="input-group mb-1">
<div class="input-group-append">
<span class="input-group-text"><em class="fas fa-inbox"></em></span>
</div>
<input type="email" name="email" id="email" class="form-control input_pass" placeholder="Email" required>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input type="checkbox" name="rememberme" class="custom-control-input" id="customControlInline">
<label class="custom-control-label" for="customControlInline">Remember me</label>
</div>
</div>
</div>
<div class="d-flex justify-content-center mt-1 login_container">
<button type="button" name="button" id="login" class="btn login_btn">Login</button>
</div>
</form>
<div class="mt-3 mb-1">
<div class="d-flex justify-content-center links">
Don't have an account? Sign Up
</div>
<div class="d-flex justify-content-center">
Forgot your password?
</div>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$(function(){
$('#login').click(function(e){
var valid = this.form.checkValidity();
if(valid){
var username = $('#username').val();
var password = $('#password').val();
var email = $('#email').val();
}
e.preventDefault();
$.ajax({
type: 'POST',
url: 'jslogin.php',
data: {username: username, password: password, email: email},
success: function(data){
alert(data);
if($.trim(data) === "1"){
setTimeout(' window.location.href = "index.php"', 1000);
}
},
error: function(data){
alert('There were errors while doing the operation.');
}
});
});
});
</script>
</body>
</html>
This is congfig.php
<?php
error_reporting(-1);
$db_user = "root";
$db_pass = "";
$db_name = "hello_world_accounts";
$db = new PDO('mysql:host=localhost;dbname='. $db_name . ';charset=utf8', $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
This is index.php
<?php
error_reporting(-1);
session_start();
if(!isset($_SESSION['hello_world_accounts'])){
header("Location: login.php");
}
if(isset($_GET['logout'])){
session_destroy();
unset($_SESSION);
header("Location: login.php");
}
?>
<!DOCTYPE>
<html lang="en">
<head>
<title>Welcome</title>
</head>
<body>
<p>Welcome to index</p>
Logout
</body>
</html>
everytime i put in my email but not my username and password it says i need to put all three in even when one is already in
why is this happening and how do I fix it?
I thought about priorities but I don't know how or what to do that...
the rest of the code on the page is as follows
Please don't say anything about having the password as plain text.
Here is my test mysql.
My Test MYSQL
Here is my test website.
My Test Website
Here's your original code when run through a formatter. You should notice, as people have pointed out, it is indented like crazy and has a lot of nesting. You are also querying the database on each request, even if the data is invalid.
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$valid = "You need to have a valid Email Address";
$sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
$stmtselect = $db->prepare($sql);
$result = $stmtselect->execute([$username, $password, $email]);
if (stripos($password, '')) {
echo 'You need to enter a Password';
} else {
if (stripos($username, '')) {
echo 'You need to enter a Username';
} else {
if (stripos($email, '')) {
echo 'You need to enter a Email Address';
} else {
if (!stripos($email, '#')) {
echo $valid;
} else {
if (!stripos($email, '.')) {
echo $valid;
} else {
if (!stripos($email, 'com')) {
echo $valid;
} else {
if ($result) {
$user = $stmtselect->fetch(PDO::FETCH_ASSOC);
if ($stmtselect->rowCount() > 0) {
$_SESSION['accounts'] = $user;
echo 'You have signed in successfully!';
} else {
echo 'Incorrect Username or Password or Email';
}
} else {
echo 'There were errors while connecting to database.';
}
}
}
}
}
}
}
Instead, here's a quick attempt at cleaning it up. The major changes are the switch to empty() checks, the usage of elseif, a better email address validator and moving the query to the final else clause.
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if (empty($password)) {
echo 'You need to enter a Password';
} elseif (empty($username)) {
echo 'You need to enter a Username';
} elseif (empty($email)) {
echo 'You need to enter a Email Address';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "You need to have a valid Email Address";
} else {
$sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
$stmtselect = $db->prepare($sql);
$result = $stmtselect->execute([$username, $password, $email]);
$user = $stmtselect->fetch(PDO::FETCH_ASSOC);
if ($stmtselect->rowCount() > 0) {
$_SESSION['accounts'] = $user;
echo 'You have signed in successfully!';
} else {
echo 'Incorrect Username or Password or Email';
}
}
EDIT
If your intention is to show multiple error messages and not just stop at the first one (as your original code does), then you can use multiple if blocks. Most people would collect the error messages in an array but I'll leave that up to you.
$isValid = true;
if (empty($password)) {
echo 'You need to enter a Password';
$isValid = false;
}
if (empty($username)) {
echo 'You need to enter a Username';
$isValid = false;
}
if (empty($email)) {
echo 'You need to enter a Email Address';
$isValid = false;
}elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "You need to have a valid Email Address";
$isValid = false;
}
if ($isValid) {
$sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
$stmtselect = $db->prepare($sql);
$result = $stmtselect->execute([$username, $password, $email]);
$user = $stmtselect->fetch(PDO::FETCH_ASSOC);
if ($stmtselect->rowCount() > 0) {
$_SESSION['accounts'] = $user;
echo 'You have signed in successfully!';
} else {
echo 'Incorrect Username or Password or Email';
}
}
EDIT
If you don't provide a method on the <form> it defaults to GET. Your code is expecting it to be POST, however. Change the form to <form method="post">.
EDIT
I'm not going to use any of your HTML and instead I'm going to just make a very simple form that POSTs to itself. This is a very common first task you learn when programming in any web language. This page, by itself, ignoring your database, styling and JS logic should work 100% by itself. Once you've proven that you can start enhancing it with sessions and then maybe AJAX. But start simple.
The form doesn't include normal settings like required or optimal types on fields intentionally because I'm just trying to keep it as simple as possible.
I did add in the errors array which removes the need for $isValid because we can now check to see if the error has anything inside of it.
Please try this code all by itself, and once you get how it works, then start modifying it, potentially asking new questions here if you really need to.
<?php
$errors = false;
$email = '';
$username = '';
$password = '';
if ('POST' === $_SERVER['REQUEST_METHOD']) {
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$errors = [];
if (empty($password)) {
$errors[] = 'You need to enter a Password';
}
if (empty($username)) {
$errors[] = 'You need to enter a Username';
}
if (empty($email)) {
$errors[] = 'You need to enter a Email Address';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "You need to have a valid Email Address";
}
}
if ($errors) {
echo '<pre>';
echo implode(PHP_EOL, $errors);
echo '</pre>';
}
?>
<form method="post">
<label>Email <input type="text" name="email" value="<?php echo htmlspecialchars($email); ?>"/></label><br/>
<label>Username <input type="text" name="username" value="<?php echo htmlspecialchars($username); ?>"></label><br/>
<label>Password <input type="password" name="password"></label><br/>
<input type="submit" value="Submit">
</form>
I am working on PHP/MYSQL register/login system for like a week and iam truly having issue with php password_hash and password_verify function...The register worked and the login with password_verify keeps failing and i do not understand why..Could somebody help out? i really am desperate.
Login part..what i am trying to achieve 1-its check if email is empty or not and if is valid email..2--its check if password is empty or not. 3-if both $email and $password are ok..it makes connection to db.. then a-it checks if the email exists in table users, if not it requires to register..b-if the user exists in db, then it verify if the $password is same as passsword in db...if it is valid password..it echoes "valid"..and if not valid password..it echoes "invalide email/password"...that is what i am trying to achieve...
Here i am posting the full code:
db design
user_id(auto_increment/primary key)
email(unique, varchar)
password(varchar, 255)
register.php
<?php
$email=$password="";
$emailErr=$passwordErr="";
if (isset($_POST['submit'])) {
if (empty($_POST['email'])) {
$emailErr="Enter your email";
}
elseif (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === FALSE) {
$emailErr = "Invalid email";
}
else
{
$email= trim($_POST['email']);
}
if (empty($_POST['password'])) {
$passwordErr = "Enter your password";
}
elseif (strlen($_POST['password']) < 3) {
$passwordErr = "password must 4 length least";
}
else
{
$password = trim($_POST['password']);
}
// if everything is filled correct connect
if ($email && $password)
{
include_once'connect.php';
$sql = "SELECT COUNT(users.email) FROM users WHERE email = :email";
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->execute();
$result = $s->fetch(PDO::FETCH_NUM);
$resultvalue = $result[0];
//if email exist, stop the script
if ($resultvalue > 0) {
echo "Email already exist";
exit();
}
// if email not exist insert it
else
{
$sql = "INSERT INTO users (email,password) VALUES (:email, :password)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':password', password_hash($password, PASSWORD_DEFAULT));
$stmt->execute();
if ($stmt) {
echo "Values inserted";
exit();
}
else
{
echo "Insert values failed";
exit();
}
}
}
//if everything is not filled correct connect
else
{
$proceedErr = "Could not proceed";
}
}//submit
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Register page</title>
<style type="text/css">
form p label
{
display: block;
}
em
{
color: red;
font-style: normal;
}
</style>
</head>
<body>
<?php
if (isset($proceedErr)) {
echo $proceedErr;
}
?>
<form method="POST" action="">
<p>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="Enter your email" value/><em><?php if(isset($emailErr)) echo $emailErr;?></em>
</p>
<p>
<label for="email">Password :</label>
<input type="password" name="password" id="password" placeholder="Enter your password" value/><em><?php if(isset($passwordErr)) echo $passwordErr;?></em>
</p>
<input type="submit" name="submit" id="submit" value="Register" />
</form>
</body>
</html>
login.php
<?php
$emailErr=$passwordErr="";
$email=$password="";
if (isset($_POST['submit'])) {
if (empty($_POST['email'])) {
$emailErr="Enter your email";
}
elseif (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === FALSE) {
$emailErr = "Enter valid email";
}
else
{
$email = trim($_POST['email']);
}
if (empty($_POST['password'])) {
$passwordErr="Enter your password";
}
else
{
$password= trim($_POST['password']);
}
if ($email && $password)
{
include_once'connect.php';
$sql = "SELECT user_id,email, password FROM users WHERE email = :email";
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->execute();
$result = $s->fetch(PDO::FETCH_ASSOC);
$resultvalue = count($result['email']);
print_r($result);
//if email do not exist, stop the script
if ($resultvalue < 1) {
echo "Your email do not exist, please register";
exit();
}
elseif (password_verify($password, $result['password'])) {
echo "valide password / email";
exit();
}
else
{
echo "InValid email / password";
exit();
}
}
else
{
echo "Email / password do not match";
}
}// end submit
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login page</title>
<style type="text/css">
form p label
{
display: block;
}
em
{
color: red;
font-style: normal;
}
</style>
</head>
<body>
<form method="POST" action="">
<p>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="Enter your email" value/><em><?php if(isset($emailErr)) echo $emailErr;?></em>
</p>
<p>
<label for="email">Password :</label>
<input type="password" name="password" id="password" placeholder="Enter your password" value/><em><?php if(isset($passwordErr)) echo $passwordErr;?></em>
</p>
<input type="submit" name="submit" id="submit" value="login" />
</form>
</body>
</html>
Tested the same scripts here and it worked.
I've received as answer "valide password / email", so this conditional statement "(password_verify($password, $result['password']))" returned true (line 51 within login.php).
Do you receive any error message or warning?
I am using foundation 5 and php for this web page.
When I go to the web page and fill in all the spaces and press create account, none of the echos are showing up on the web page. The page just refreshes and just makes a new page like if I just reloaded the page. No text shows up and none of the function are working.
Here is my code:
<?php
error_reporting(0);
#ini_set('display_errors', 0);
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AskmanProducts</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
<script src="js/signinvaldator.js"></script>
</head>
<body>
<?php
if ($_POST['registerbtn']) {
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$getpass = $_POST['pass'];
$getconfirmpass = $_POST['confirmpass'];
if ($getuser) {
if ($getemail) {
if ($getpass){
if ($getconfirmpass) {
if ($getpass === $getconfirmpass) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
require ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email='$getemail'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$password = md5(md5("kjfiufj".$getpass."Fj56fj"));
$date = date("F d, Y");
$code = md5(rand());
mysql_query("INSERT INTO users VALUES (
'', '$getuser', '$password', '$getemail', '0', '$code', '$date'
)");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$site = "http://localhost/Projects/project";
$webmaster = "donotreply#askmanproducts.com";
$headers = "From: $webmaster";
$subject = "Activate Your Account";
$message = "Thanks For Registering. Click The Link Below To Activate Your Account.\n";
$message .= "$site/activate.php?user=$getuser&code=$code\n";
$message .= "You Must Activate Your Account To Login.";
if (mail($getemail, $subject, $message, $headers)) {
echo "You have been registered. You must activate your account from the activation link sent to <b>$getemail</b>";
$getuser = "";
$getemail = "";
}
else {
echo "An error has occured. You activation email was not sent.";
}
}
else {
echo "An error has occured. Your account was not created.";
}
}
else {
echo "There is already a user with that email.";
}
}
else {
echo "There is already a user with that username.";
}
mysql_close();
}
else {
echo "You must enter a valid email address to register.";
}
}
else {
echo "Your password do not match.";
}
}
else {
echo "You must confirm your password to register.";
}
}
else {
echo "You must enter your password to register.";
}
}
else {
echo "You must enter your email to register.";
}
}
else {
echo "You must enter your username to register.";
}
}
else {
}
$form = "<form action='register.php' method='post'>
<div class='row' style='margin-top:10%'>
<div align='center'><h2>Create an Account</h2></div>
<br />
<div class='medium-6 medium-centered large-centered large-6 columns'>
<form data-abide>
<div class='name-field'>
<label>Username</label>
<input type='text' name='user' value='$getuser'></input>
<div class='email-field'>
<label>Email</label>
<input type='email' name='email' value='$getemail'></input>
<label for='password'>Password</label>
<input type='password' name='pass' value=''></input>
<label for='confirmPassword'>Confirm Password</label>
<input type='password' name='confirmpass' value=''></input>
<br />
<br />
<button type='submit' name='registerbtn'>Create Account</button>
<a href='login.php' class='button'>Log In</a>
<br />
</form>
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
</form>";
echo $form;
?>
</body>
</html>
Your form has action='register.php' as its destination. When you do this, by pressing the Submit button, the page will jump to register.php before giving your error checking code any chance to fire.
I recommend you use
action='<?php echo $_SERVER['PHP_SELF']; ?>'
so that your Submit button keeps you on the same page, then when your error checking process passes, use:
header('Location: register.php');
Either that, or pass each of your POST variables to register.php where the error checking is carried out.
In this solution I have altered your code considerably but I use this logic all the time on my sites. I'll explain the code under it.
NOTE:
I did review your processing but did not test... Judging from the initial comments you are getting outdated information regarding programming. your mysql query code is outdated and depreciated and you should be making use of parameterised queries as pointed out in the comments by #Dave below this answer.
I suggest you go to youtube and search for pdo tutorials to learn modern methods of querying mysql. The provided code shows how to process forms through jQuery and a processing php file.
HTML & jQuery
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AskmanProducts</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
<script src="js/signinvaldator.js"></script>
</head>
<body>
<input type="hidden" name="processRegistrationURL" value="register.php">
<div id="showRegistrationResults" class="row" style="margin-top:10%">
<div align="center"><h2>Create an Account</h2></div>
<br />
<div class="medium-6 medium-centered large-centered large-6 columns">
<form data-abide>
<div class="name-field">
<label>Username</label>
<input type="text" is="user" name="user" value="$getuser"></input>
<div class="email-field">
<label>Email</label>
<input type="email" id="email" name="email" value="$getemail"></input>
<label for="password">Password</label>
<input type="password" id="pass" name="pass" value=""></input>
<label for="confirmPassword">Confirm Password</label>
<input type="password" id="confirmpass" name="confirmpass" value=""></input>
<br />
<br />
<button type="submit" id="registerbtn" name="registerbtn">Create Account</button>
Log In
<br />
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
<script>
$(function() {
$( "#registerbtn" ).click(function(){
var url = $('#processRegistrationURL').val();
var user = $('#user').val();
var email = $('#email').val();
var pass = $('#pass').val();
var confirmpass = $('#confirmpass').val();
var postit = $.post( url, {
user:user,
email:email,
pass:pass,
confirmpass:confirmpass
});
postit.done(function( data ) {
var result = data.split('|');
if(result[0] == 1){alert(result[1]);}
else if(result[0] == 2){
$('#showRegistrationResults').html(result[1]);
}
});
});
});
</script
</body>
</html>
There are no form tags... the form processing is handled on register.php which is stored in a hidden input <input type="hidden" name="processRegistrationURL" value="register.php">
I have added id to each form and the submit button.
register.php
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$getpass = $_POST['pass'];
$getconfirmpass = $_POST['confirmpass'];
if ($getuser) {
if ($getemail) {
if ($getpass){
if ($getconfirmpass) {
if ($getpass === $getconfirmpass) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
require ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email='$getemail'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$password = md5(md5("kjfiufj".$getpass."Fj56fj"));
$date = date("F d, Y");
$code = md5(rand());
mysql_query("INSERT INTO users VALUES (
'', '$getuser', '$password', '$getemail', '0', '$code', '$date'
)");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$site = "http://localhost/Projects/project";
$webmaster = "donotreply#askmanproducts.com";
$headers = "From: $webmaster";
$subject = "Activate Your Account";
$message = "Thanks For Registering. Click The Link Below To Activate Your Account.\n";
$message .= "$site/activate.php?user=$getuser&code=$code\n";
$message .= "You Must Activate Your Account To Login.";
if (mail($getemail, $subject, $message, $headers)) {
echo "You have been registered. You must activate your account from the activation link sent to <b>$getemail</b>";
$getuser = "";
$getemail = "";
}
else {
echo "2|An error has occurred. You activation email was not sent. Please refresh this page and try again. If this issue persists please contact administration.";
}
}
else {
echo "2|An error has occurred. Your account was not created. Please refresh this page and try again. If this issue persists please contact administration.";
}
}
else {
echo "1|There is already a user with that email.";
}
}
else {
echo "1|There is already a user with that username.";
}
mysql_close();
}
else {
echo "1|You must enter a valid email address to register.";
}
}
else {
echo "1|Your password do not match.";
}
}
else {
echo "1|You must confirm your password to register.";
}
}
else {
echo "1|You must enter your password to register.";
}
}
else {
echo "1|You must enter your email to register.";
}
}
else {
echo "1|You must enter your username to register.";
}
else {
echo "2|WHATEVER YOU WANT TO RENDER IN #showRegistrationResults";
}
When the button is clicked it fires the jQuery which in turn passes the form submission to register.php
You will notice in each echo there is a 1 or a 2 with a pipe. echo "1|You must enter your password to register.php"; The echo will return to the jQuery as data.
The jQuery then splits the data at the pipe (|). If result[0] == 1 the jQuery fires an alert leaving the form intact for corrections to be made. If result[0] == 2 the jQuery will replace the content of #showRegistrationResults which wraps the form (it will replace the form) with the data returned through the echo.
Review the echos on register.php. The first two replace the form as an error in processing has occurred. All other return an alert message.
You can toggle these as desired.
Improve your password security
You can improve your password security with the following code:
$hash_key = trim(file_get_contents('PATH-TO/key.dat'));
$password = hash_hmac('sha512', $getpass, $hash_key);
key.dat simply contains a key: for example: 72093OT7Yw6g0925T9Ly07G6y7WhI2v5
Hope this helps
Pete
Trying to create a registration page that adds new users to a database with php, i can't seem to get the information to add to the database, it is most likely something stupid that I have doing wrong or have missed out in my code.
Here is my code
<?php
session_start();
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="author" content="" />
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="boilerplate/js/vendor/modernizr-2.7.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="../css/party.css" media="screen" />
<script type="text/javascript" src="javascript/jquery_min.js"></script>
<script type="text/javascript" src="javascript/cookies.js"></script>
</head>
<body>
<?php include 'header.php'; ?>
<div id="container_register">
<div id="content_register">
<h2>Register</h2>
<?php
include "connect.php";
if (isset($_POST['formsubmitted'])) {
$error = array(); //Declare An Array to store any error message
if (empty($_POST['up_username'])) { //if no name has been supplied
$error[] = 'Please Enter a name '; //add to array "error"
} else {
$name = $_POST['up_username']; //else assign it a variable
}
if (empty($_POST['up_email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",
$_POST['up_email'])) {
//regular expression for email validation
$Email = $_POST['up_email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['up_password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['up_password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM users WHERE Email ='$Email'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) { //if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$query_insert_user =
"INSERT INTO `users` ( `Username`, `Email`, `Password`) VALUES ( '$name', '$Email', '$Password')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
echo '<div class="success">Thank you for
registering! </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a systemdiv>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email address has already been registered.</div>';
}
} else { //If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc); //Close the DB Connection
// End of the main Submit conditional.
?>
<form name="signup" id="signup" action="register.php" method="post">
<label for="up_username"><span class="required">*</span> Name</label>
<input type="text" name="up_username" id="up_username" placeholder="First Surname" />
<br>
<label for="up_email"><span class="required">*</span> Email</label>
<input type="email" name="up_email" id="up_email" placeholder="username#email.com" />
<br>
<label for="up_password"><span class="required">*</span> Password</label>
<input type="password" name="up_password" id="up_password" />
<br>
<label for="up_password_c"><span class="required">*</span> Confirm Password</label>
<input type="password" name="up_password_c" id="up_password_c" />
<div class="div_submit">
<input id="register_submit" type="submit" value="Sign up" />
</div>
</form><!--#sign up end-->
<p class="required">* Indicates a required field</p>
</div><!--content div end-->
</div><!--container div end-->
The If conditions you have written is always retrun false.
To Resolve this Please set the name attribute of submit button to formsubmitted like as follows
<input id="register_submit" name= "formsubmitted" type="submit" value="Sign up" />
Since the formsubmitted is not present inside the form the values is not set for $_POST['formsubmitted'], So the If part of your if statement is never executed.
Here is a similar script I often use, feel free to alter it at your discretion.
<?
if ($_POST['submit']){
$username = $_POST['username'];
$password = md5($_POST['password']);
$confirm = $_POST['confirm'];
$email = $_POST['email'];
if (!$username || !$password || !$confirm || !$email){
$response = "Please fill in all the boxes";
}else{
$check = mysql_num_rows(mysql_query("SELECT * FROM users WHERE username='$username'"));
if ($check != 0){
$response = "Username taken, Please choose an alternative";
}else{
$check = mysql_num_rows(mysql_query("SELECT * FROM users WHERE email='$email'"));
if ($check != 0){
$response = "This Email has already been registered";
}else{
mysql_query("INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES ('', '$username', '$password', '$email');");
$response = "Account Created";
}
}
}
}
echo "$response"; ?>
I am trying to create a registration page in PHP with MYSQL . My index.php page has a form which I have to fill in , and upon registration , it is supposed to show the status of registration , whether it is successful or not , and whether confirmation link is being sent to the email. However , when I click register , it redirects to register.php where nothings is being shown - all i see is a blank page no matter what info i key in. Furthermore , upon checking my table (user) in database (users) , I realized that no data is being input. My database connection is correct since I have verified it and i suspect that the error is in register.php . can anyone take a look at it and guide me on what I might be doing wrong? Thanks in advance.
my index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sign Up</title>
<style>
label{
width:100px;
float:left;
}
</style>
</head>
<body>
<?php
session_start();
if(isset($_SESSION['error']))
{
echo '<p>'.$_SESSION['error']['username'].'</p>';
echo '<p>'.$_SESSION['error']['email'].'</p>';
echo '<p>'.$_SESSION['error']['password'].'</p>';
echo '<p>'.$_SESSION['error']['mail_add'].'</p>';
unset($_SESSION['error']);
}
?>
<div class="signup_form">
<form action="register.php" method="post" >
<p>
<label for="username">User Name:</label>
<input name="username" type="text" id="username" size="30"/>
</p>
<p>
<label for="email">E-mail:</label>
<input name="email" type="text" id="email" size="30"/>
</p>
<p>
<label for="password">Password:</label>
<input name="password" type="password" id="password" size="30 "/>
</p>
<p>
<label for="mail_add">Mailing:</label>
<input name="mail_add" type="text" id="mail_add" size="30"/>
</p>
<p>
<input name="submit" type="submit" value="Submit"/>
</p>
</form>
</div>
</body>
</html>
My register.php
<?php
session_start();
include('configdb.php');
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['username'] == '')
{
$_SESSION['error']['username'] = "User Name is required.";
}
if($_POST['mail_add'] == '')
{
$_SESSION['error']['mail_add'] = "Mailing address is required.";
}
//whether the email is blank
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = "E-mail is required.";
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$sql1 = "SELECT * FROM user WHERE email = '$email'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
if (mysqli_num_rows($result1) > 0)
{
$_SESSION['error']['email'] = "This Email is already used.";
}
}
else
{
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = "Password is required.";
}
//if the error exist, we will go to registration form
if(isset($_SESSION['error']))
{
header("Location: index.php");
exit;
}
else
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$mail_add = $_POST['mail_add'];
$com_code = md5(uniqid(rand()));
$sql2 = "INSERT INTO user (username, email, password, com_code , mail_add) VALUES ('$username', '$email', '$password', '$com_code', '$mail_add')";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
if($result2)
{
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$message .= "http://www.yourname.com/confirm.php?passkey=$com_code";
$sentmail = mail($to,$subject,$message,$header);
echo "Records finally inserted into table.";
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
}
else {
echo "Cannot insert into table";
}
}
}
?>
Thanks in advance.
Try:
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error($mysqli));
Enjoy your code