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"; ?>
Related
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");
}
}
}
?>
I have a PHP script where I want to verify a valid email address using filter_var() but it is not working.
html form:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>CRUD Operations</title>
</head>
<body>
<div id="container"><!--container-->
<div id="wrapper">
<div id="form-element">
<div id="headings">
<h1>PHP Contact Form</h1>
</div>
<form method="post" action="operations.php" enctype="multipart/form-data">
<span>Name:</span><br>
<input type="text" name="name" value=""><br><br>
<span>Email:</span><br>
<input type="text" name="mail" value=""><br><br>
<span>Gender:</span><br>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
<span>Message</span><br>
<div id="message">
<textarea cols="36" rows="4" name="message"></textarea><br>
</div>
<div id="submit">
<input type="submit" value="Submit" name="submit">
</div>
</form>
</div>
</div>
</div><!--container-->
</body>
</html>
php code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>CRUD Operations</title>
</head>
<?php
include_once('config.php');
$name = $mail = $gender = $message = '';
$email_err = '';
if(isset($_POST['submit'])){
$name= $_POST['name'];
$mail = $_POST['mail'];
if(!isset($_POST['gender'])){
}
else {
$gender = $_POST['gender'];
}
$message = $_POST['message'];
if(empty($name) || empty($mail) || empty($gender)|| empty($message)) {
if(empty($name)){
echo'<div class="error">*Dear User fill the Name field properly</div>';
}
if(empty($mail)){
echo'<div class="error">*Dear User fill the Email field properly</div>';
}
else {
if(!filter_var($mail, FILTER_VALIDATE_EMAIL)){
$email_err = "*valid Email is required";
}
}
if(empty($gender)){
echo'<div class="error">*Dear User please select your gender</div>';
}
if(empty($message)){
echo'<div class="error">*Dear User please Leave your Message</div>';
}
}
else {
$query = mysql_query("INSERT INTO users(`name`, `mail`, `gender`, `message`) VALUES('".$name."','".$mail."','".$gender."','".$message."')");
if($query) {
echo '<div class="success">Congratulations You Are Registered Successfully</div>';
echo 'View Records';
}
else {
echo 'not';
}
}
}
?>
</html>
Any help would be appreciated!
You're setting the validation error to the $email_err variable, but you're not doing anything with that variable after that.
But more importantly, the filter_var() call will never be hit. You have it in the block that checks for any of $name $mail $gender $messsage are empty. So the only way to get your code to do an email validation would be if someone entered an email address, but left gender blank.
You need to move the filter_var() call out of that block:
if(empty($name) || empty($mail) || empty($gender)|| empty($message)) {
if(empty($name)){
echo'<div class="error">*Dear User fill the Name field properly</div>';
}
if(empty($mail)){
echo'<div class="error">*Dear User fill the Email field properly</div>';
}
if(empty($gender)){
echo'<div class="error">*Dear User please select your gender</div>';
}
if(empty($message)){
echo'<div class="error">*Dear User please Leave your Message</div>';
}
}
elseif(!filter_var($mail, FILTER_VALIDATE_EMAIL)){
echo'<div class="error">*valid Email is required</div>';
}
else {
$query = mysql_query("INSERT INTO users(`name`, `mail`, `gender`, `message`) VALUES('".$name."','".$mail."','".$gender."','".$message."')");
if($query) {
echo '<div class="success">Congratulations You Are Registered Successfully</div>';
echo 'View Records';
}
else {
echo 'not';
}
}
When I write validation code such as this I try to avoid using conditionals that check so many things at once. Instead, validate each input in turn and abort if that is not valid; returning an error to the user at that point. Then you could move all of this validation to a single sub-routine. In this routine, if any validation checks fail - it returns immediately with an error. Only if your sub-routine makes it to the end would a user be created. And it prevents one from checking a variable $mail and then later validating it after it's already passed your truth check.
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
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
I am currently trying to create a registration form, and I have the form itself working and people can create user's in my database, but when they sign up and it redirects them to the admin.php.
The name they used to create an account doesn't show up, down by row user name. It should say "Welcome, user_name, you are now logged in!"
I just can't get the name to show up but everything else works!
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\path\to\admin.php on line 25
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\path\to\login.php on line 36
Admin:
<?php
require('db_config.php');
require_once('functions.php');
//if the cookie is still valid, recreate the session
if( $_COOKIE['logged_in'] == true ){
$_SESSION['logged_in'] = true;
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['is_admin'] = $_COOKIE['is_admin'];
}
if( $_SESSION['logged_in'] != true ){
//not logged in! send them back to the form]
header('location:login.php');
}
//extract the data for the logged in user, so we can use it on all page
$user_id = $_SESSION['name'];
$query_user = "SELECT * FROM users
WHERE name = $user_id
LIMIT 1";
$result_user = mysql_query($query_user);
$row_user = mysql_fetch_array($result_user);
//this going to be a handy variable to have throughout all pages
$user_id = $row_user['user_id'];
?>
<!doctype HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/reset.css" />
<link rel="stylesheet" type="text/css" href="css/format.css" />
<title>Schell Shock Design's Portfolio</title>
</head>
<body>
<div id="login">
<?php
include('login.php');
?>
</div>
<div id="utilities">
<?php include('utilities.php'); ?>
</div>
<div id="container">
<header>
<?php include('header.php'); ?>
</header>
<div id="slider">
<?php include('slider.php'); ?>
</div>
<div id="content">
<?php include('content.php'); ?>
</div>
<div id="bottomcontent">
<?php include('bottomcontent.php'); ?>
</div>
<div id="footer">
<?php include('footer.php'); ?>
</div>
</body>
</html>
Login:
<?php
//show an error if there is a problem with the login
if($error == true){ ?>
<div class="error">
Sorry, Your username and password are incorrect. Try again.
</div>
<?php } //end if error ?>
<?php //show the form only if NOT logged in
if( !$_SESSION['logged_in'] ){
?>
<div class="form1">
<form action="?action=" method="post">
<label for="username">Username:</label>
<input type="text" name="username" id="username" />
<label for="password">Password</label>
<input type="password" name="password" id="password" />
<input type="submit" value="Log in" />
<input type="hidden" name="did_login" value="1" />
</form>
<?php } //end if not logged in
else{
//get info of logged in person
$user_id = $_SESSION['user_id'];
$query_user = "SELECT name
FROM users
WHERE user_id = $user_id";
$result_user = mysql_query( $query_user );
$row_user = mysql_fetch_array( $result_user );
?>
<div id="loggedin">
Log Out
<?php //show a welcome message if they logged in successfully
echo 'Welcome '.$row_user['name'].', You are now logged in!';
?>
<?php } ?>
</div>
Registration
<?php
//register parse. all this logic MUST go before the doctype or any other text output.
require('db_config.php');
require_once('functions.php');
//if they submitted the form, parse it
if( $_POST['did_register'] == 1 ){
//extract amd sanitize all fields
$username = clean_input($_POST['username']);
$email = clean_input($_POST['email']);
$password = clean_input($_POST['password']);
$repassword = clean_input($_POST['repassword']);
$policy = clean_input($_POST['policy']);
//encrypted version of the password, for storing in the database
$sha_password = sha1($password);
//begin validation
$valid = true;
//did they forget to check the box?
if( $policy != 1 ){
$valid = false;
$msg = 'You must agree to the TOS and PP before signing up. <br />';
}
//repeated password does not match
if( $password != $repassword ){
$valid = false;
$msg .= 'The passwords provided do not match. <br />';
}
//make sure the username and password are at least 5 characters long, than check the database
if( strlen($username) >= 5 AND strlen($password) >= 5 ){
//check to see if username is already taken
$query_username = "SELECT name
FROM users
WHERE name = '$username'
LIMIT 1";
$result_username = mysql_query($query_username);
//if one result is found, username is taken.
if( mysql_num_rows($result_username) == 1 ){
$valid= false;
$msg .= 'That username is already taken. Try another. <br />';
}
}else{
$valid = false;
$msg .= 'Username and Password must be at least 5 characters long. <br />';
}
//check for valid email, than check for match in database
if( check_email_address($email) == true ){
//look for match in database
$query_email = "SELECT email
FROM users
WHERE email = '$email'
LIMIT 1";
$result_email = mysql_query($query_email);
//if 1 result is found, email is taken.
if( mysql_num_rows($result_email) == 1 ){
$valid = false;
$msg .= 'Looks like an account with that email already exists. Do you want to login? <br />';
}
}else{
//invalid email
$valid = false;
$msg .= 'Please provide a valid email address. <br />';
}
//if the data passed ALL tests, add the user to the database
if( $valid == true ){
$query_insert = "INSERT INTO users
(name, password, email, join_date, is_admin)
VALUES
('$username', '$sha_password', '$email', now(), 0)";
$result_insert = mysql_query($query_insert);
//check to see if it worked
if( mysql_affected_rows() == 1 ){
//SUCCESS! Log the user in and send them to their profile.
$_SESSION['logged_in'] = true;
setcookie( 'logged_in', 'true', time() + 60*60*24*7 );
header( 'location:index.php' );
}else{
$msg .= 'There was a problem adding the user to the Database';
}
}
} //end if submitted form
?>
<!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 for an account</title>
</head>
<body>
<?php
if( isset($msg) ){
echo $msg;
}
?>
<form action="registration.php" method="post">
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username" />
<span class="hint">Minimum of five characters</span>
<label for="email">Your Email Address:</label>
<input type="text" name="email" id="email" />
<label for="password">Choose a Password:</label>
<input type="password" name="password" id="password" />
<span class="hint">Minimum of 5 characters</span>
<label for="repassword">Repeat Password:</label>
<input type="password" name="repassword" id="repassword" />
<input type="checkbox" name="policy" id="policy" value="1" />
<label for="policy">Yes, I have read the Terms of Service and Privacy Policy.</label>
<input type="submit" value="Sign up" />
<input type="hidden" name="did_register" value="1" />
</form>
</body>
</html>
What do I need to fix?
You should check what the error is:
if (!$result_user) {
die('MySQL Error: '.mysql_error());
}
Call session_start() at the top of each of your pages.
And ensure session's values are returned correctly:
print_r($_SESSION);
In admin.php, this query is failing:
$query_user = "SELECT * FROM users WHERE name = $user_id LIMIT 1";
Maybe $user_id is empty, or it needs to be quoted ('$user_id').
In any case you should be checking the result of the query to make sure it was successful:
$user_id = $_SESSION['name'];
$query_user = "SELECT * FROM users
WHERE name = $user_id
LIMIT 1";
$result_user = mysql_query($query_user);
if (!$result_user) {
die('Query failed: ' . mysql_error());
}
mysql_query() only returns a resource result on success. On failure, it returns (bool)FALSE which cannot be passed to any mysql_fetch_* functions.
The same is the case for the error in login.php.
You don't seem to be showing the code that runs upon login, my guess is you are not assigning the right variables to the session.