I am creating an update form, but when I click on the update button it redirects to my update page, and triggers the POST request which makes it a valid post and does not ask for any information to update.
<!DOCTYPE html>
<html>
<?php require ('template/functions.php');
$ID = $_GET['id'];
$sql_query = "SELECT * FROM specialties WHERE id='".$ID."'";
$results = mysqli_query($connect,$sql_query);
$spc = mysqli_fetch_assoc($results);
$error = "";
$specialist_section = false;
$description_section = false;
$specilist_exist = false;
$valid_post = true;
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "post") {
valid();
if ($valid_post){
$sql_query = "UPDATE specialties SET ";
$sql_query .= "specialty='".$_POST['specialty']."',";
$sql_query .= "description='".$_POST[description]."'";
$sql_query .= " WHERE id='".$_GET['id']."'";
$result = mysqli_query($connect,$sql_query);
if (!results){
print "MYSQL_ERROR: ".mysqli_error($connect);
$valid_post = false;
$specilist_exist = true;
$error .= "Specialty already exist <br/>";
}
}else{
$valid_post = false;
}
}
?>
<head>
<title>Specialist Lookup </title>
</head>
<body>
<div class="container">
<?php
if ($valid_post){?>
<h2>Update Complete</h2>
<?php
}else{
if ($error) { ?>
<h3 style="color:red;"><?php echo $error ?> </h3> <?php }?>
<h1>Update Specialist</h1>
<form action="update.php" method="post">
<div class="form-group">
<label for="specialty" style="color:<?php if ($specialist_section){echo "red";}else{ echo "black";} ?>">Specialty:</label>
<input type="text" class="form-control" id="sp" name="specialty" value="<?php echo $spc['specialty'] ;?>" >
</div>
<div class="form-group">
<label for="description" style="color:<?php if ($description_section){echo "red";}else{ echo "black";} ?>">Description:</label>
<textarea class="form-control" rows="5" id="comment" name="description"><?php echo $spc['description'] ; ?></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<?php
}
?>
<div>
</body>
<?php
require ('template/footer.php');
?>
/*Reference for the function*/
function valid(){
$valid_post = true;
if (empty($specialty)) {
$valid_post = false;
$specialist_section = true;
$error = "Please fill in the Specialist section";
}
elseif (empty($description)) {
$valid_post = false;
$error = "Please fill in the description section";
$description_section = true;
}
elseif (empty($description) and empty($specialty)) {
$valid_post = false;
$error = "Please fill in the specialty and description section";
$description_section = true;
}
else{
$valid_post = true;
}
}
By default you set
$valid_post = true;
You need to change the logic:
<!DOCTYPE html>
<html>
<?php require ('template/functions.php');
...
$valid_post = false;
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "post") {
$valid_post = valid();
if ($valid_post){
// ...
}
}
?>
<head>
<title>Specialist Lookup </title>
</head>
<body>
<div class="container">
<?php
if ($valid_post){?>
<h2>Update Complete</h2>
<?php
}else{
// ...
}
?>
<div>
</body>
I do not know what happens in valid() function. But I suggest you this pattern:
$validPost = false;
if (valid()) {
$validPost = true;
}
or
$validPost = valid();
Not too sure how you write your valid() function.
By looking at the code, $valid_post is set to be true by default, so you might want to have a look at your valid() function to see if it is actually setting $valid_post to be false if it is not valid, otherwise it will always trigger your update function even if there is no valid form data.
if your valid() function is returning boolean then just modify your code
change
valid()
to
$valid_post = valid()
Also, you probably dont need else in your code at all, $valid_post = valid() this will simply assign a boolean value already, therefore the else part will be redundant.
Let me know if you have any question
Related
I'm new to PHP and I'm trying to create an easy form that has multiple steps. For each step, a validation of the input is happening before the user is directed to the next page. If the validation fails, the user should stay on the same page and an error message should be displayed. In the end, all entries that the user has made should be displayed in an overview page.
What I have been doing to solve this, is to use a boolean for each page and only once this is true, the user can go to the next page. This is not working as expected unfortunately and I guess it has something to do with sessions in PHP... I also guess that there's a nicer way to do this. I would appreciate some help!
Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
session_start();
$_SESSION['$entryOne'] = "";
$_SESSION['$entryOneErr'] = $_SESSION['$emptyFieldErr'] = "";
$_SESSION['entryOneIsValid'] = false;
$_SESSION['$entryTwo'] = "";
$_SESSION['$entryTwoErr'] = "";
$_SESSION['entryTwoIsValid'] = false;
// Validation for first page
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryOne'])) {
if (!empty($_POST["entryOne"])) {
// Check for special characters
$_SESSION['$entryOne'] = removeWhitespaces($_POST["entryOne"]);
$_SESSION['$entryOneErr'] = testForIllegalCharError($_SESSION['$entryOne'], $_SESSION['$entryOneErr']);
// If error text is empty set first page to valid
if(empty($_SESSION['$entryOneErr'])){
$_SESSION['$entryOneIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
// Validation for second page
} else if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryTwo'])) {
if (!empty($_POST["entryTwo"])) {
// Check for special characters
$_SESSION['$entryTwo'] = removeWhitespaces($_POST["entryTwo"]);
$_SESSION['$entryTwoErr'] = testForIllegalCharError($_SESSION['$entryTwo'], $_SESSION['$entryTwoErr']);
// If error text is empty set second page to valid
if(empty($_SESSION['$entryTwoErr'])){
$_SESSION['$entryTwoIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
}
//Remove whitespaces at beginning and end of an entry
function removeWhitespaces($data) {
$data = trim($data);
return $data;
}
//Check that no special characters were entered. If so, set error
function testForIllegalCharError($wish, $error){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar,$wish)) {
$error = "Special characters are not allowed";
} else {
$error = "";
}
return $error;
}
?>
<?php if (isset($_POST['submitEntryOne']) && $_SESSION['$entryOneIsValid'] && !$_SESSION['$entryTwoIsValid']): ?>
<h2>Second page</h2>
<p>Entry from first Page: <?php echo $_SESSION['$entryOne'];?></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Entry Two: <input type="text" name="entryTwo" value="<?php echo $_SESSION['$entryTwo'];?>">
<span class="error"><?php echo $_SESSION['$entryTwoErr'];?></span>
<br><br>
<input type="submit" name="submitEntryTwo" value="Next">
</form>
<?php elseif (isset($_POST['submitEntryTwo']) && $_SESSION['$entryTwoIsValid']): ?>
<h2>Overview</h2>
<p>First entry: <?php echo $_SESSION['$entryOne'];?></p>
<p>Second Entry: <?php echo $_SESSION['$entryTwo'];?></p>
<?php else: ?>
<h2>First page</h2>
<span class="error"><?php echo $_SESSION['$emptyFieldErr'];?></span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br><br>
First entry: <input type="text" name="entryOne" value="<?php echo $_SESSION['$entryOne'];?>">
<span class="error"> <?php echo $_SESSION['$entryOneErr'];?></span>
<br><br>
<input type="submit" name="submitEntryOne" value="Next">
</form>
<?php endif; ?>
</body>
</html>
You are setting your session variables to "" at the top of your script.
Check if your variable is set before setting to blank.
Check if Session Variable is Set First
<?php
//If variable is set, use it. Otherwise, set to null.
// This will carry the variable session to session.
$entryOne = isset($_REQUEST['entryOne']) ? $_REQUEST['entryOne'] : null;
if($entryOne) {
doSomething();
}
?>
Tips
Then you can use <?= notation to also echo the variable.
Do this $_SESSION['variable'] instead of $_SESSION['$variable'] (you'll spare yourself some variable mistakes).
<h2>Second page</h2>
<p>Entry from first Page: <?= $entryOne ?></p>
Example Script
This could be dramatically improved, but for a quick pass:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Check that no special characters were entered. If so, set error
function hasIllegalChar($input){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar, $input)) {
return true;
}
return false;
}
session_start();
// Destroy session and redirect if reset form link is pressed.
if(isset($_GET['resetForm']) && $_GET['resetForm'] == "yes")
{
echo "SESSION DESTROY";
session_destroy();
header("Location: ?");
}
// Session
$page = isset($_SESSION['page']) ? $_SESSION['page'] : 1;
$errors = [];
// Value history.
$valueOne = isset($_SESSION['valueOne']) ? $_SESSION['valueOne'] : null;
$valueTwo = isset($_SESSION['valueTwo']) ? $_SESSION['valueTwo'] : null;
// Clean inputs here
$fieldOne = isset($_REQUEST['fieldOne']) ? trim($_REQUEST['fieldOne']) : null;
$fieldTwo = isset($_REQUEST['fieldTwo']) ? trim($_REQUEST['fieldTwo']) : null;
// First form
if ($page == 1) {
// If field two is submitted:
if ($fieldOne) {
//Validate inputs
if(hasIllegalChar($fieldOne)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueOne = $_SESSION['valueOne'] = $fieldOne;
$page = $_SESSION['page'] = 2;
}
}
}
// Second form
else if ($page == 2) {
// If field two is submitted:
if ($fieldTwo) {
//Validate inputs
if(hasIllegalChar($fieldTwo)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueTwo = $_SESSION['valueTwo'] = $fieldTwo;
$page = $_SESSION['page'] = 3;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
// troubleshoot
if (true) {
echo "<pre>";
var_dump($_REQUEST);
var_dump($_SESSION);
echo "</pre>";
}
echo "<h1>Page " . $page . '</h1>';
if (count($errors) > 0) {
$errorMsg = implode('<br/>',$errors);
echo '<div class="error">Some errors occurred:<br/>' . $errorMsg . '</div>';
}
?>
<?php if ($page == 3): ?>
<h2>Overview</h2>
<p>First entry: <?= $valueOne;?></p>
<p>Second Entry: <?= $valueTwo;?></p>
Reset
<?php elseif ($page == 2): ?>
<p>Entry from first Page: <?= $valueOne; ?></p>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
Entry Two: <input type="text" name="fieldTwo" value="<?= $fieldTwo ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php else: ?>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
<br><br>
Entry One: <input type="text" name="fieldOne" value="<?= $fieldOne; ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php endif; ?>
</body>
<html>
You can run the following command to test out the page without using a fancy tool like WAMP or LAMP.
php -S localhost:8000 index.php
You can now access in the browser at http://localhost:8000.
I'm having some trouble displaying my errors on this login form.
The login works but I can't figure out how to display those errors.
I just need to display them between the login field and the footer. I suppose the problem should be the last part of the foreach that should go true the error array.
<!DOCTYPE html>
<html lang="en">
<body>
<?php
include ('includes/header.php');
?>
<div class="nav">
<?php
include ('includes/menu.php');
$error= logInData();
?>
</div>
<section role="main">
<div class="logIn">
<h3>Intranet Login</h3>
</div>
<form action="" method="post">
<fieldset>
<legend>Student Log in</legend>
<div>
<label for="username">Enter username: </label>
<input type='text' id="userN" name="userN" value = "<?php if (isset($error['usern'])){echo $error['usern'];} ?>">
</div>
<div>
<label for="password">Enter password: </label>
<input type='password' id="pass" name="pass" value = "">
</div>
<div>
<p class="red"><?php if (isset($error['both'])) {
echo $error['both'];
} ?></p>
</div>
<div>
<input type="submit" name="submit" value="Log-In">
</div>
</fieldset>
</form>
</section>
<?php
function logInData (){
$error = array();
$validated = array();
$clean = array();
$pass = false;
if (isset($_POST['submit']) && $pass == true) {
$inputPass = ($_POST['pass']);
$trimPass = trim($inputPass);
$inputUsern = ($_POST['userN']);
$trimUsern = trim($inputUsern);
if(!empty($trimPass)){
if (!ctype_alpha($trimPass)) {
$error['passw'] = 'No special characters allowed on password';
$pass = false;
}else{
if(empty($trimPass)){
$error['passw'] = 'password field empty';
$pass = false;
}else{
$clean['passw'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
if(!empty($trimUsern)){
if (!ctype_alpha($trimUsern)) {
$error['userN'] = 'No special characters allowed on username';
$pass = false;
}else{
if(empty($trimPass)){
$error['userN'] = 'username field empty';
$pass = false;
}else{
$clean['userN'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
$dir = '/home/sbau01/public_www/php/fma/data';
if (is_dir($dir)){
$handleDir = opendir('/home/sbau01/public_www/php/fma/data');
$path = "/home/sbau01/public_www/php/fma/data/data.txt";
if(is_file($path)){
$handle = fopen($path, 'r');
while(!feof($handle)){
$dataRow = fgets($handle);
if(!empty($dataRow)){
$separate = explode(' ',$dataRow);
$storedUsern = trim($separate[3]);
$storedPassword = trim($separate[4]);;
if (($clean['userN'] == $storedUsern) && ($clean['passw'] && $storedPassword)){
$match = true;
header('location: intranet.php');
}else{
$error['match']='<span >Username/Password is incorrect!!</span>';
$pass = false;
}
}
}fclose($handle);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}closedir($HandleDir);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}
}else {
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
}
}
?>
<footer>
<?php include ('includes/footer.php');?>
</footer>
</body>
</html>
Its a simple brackets error:
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
The part above is in the else condition of if (isset($_POST['submit']) && $pass == true) {
Thats why this will never execute. Simply remove the bracket above this part and add it after the foreach.
Saving Passwords in text files is NOT a great idea!
In line 101 you have probably an little mistake:
You just check if there are the variables, you dont check if they are equal ($clean['passw'] && $storedPassword)){
A couple of issues identified.
Do you have display errors turned on? https://stackoverflow.com/a/21429652/1246494
You are calling $error= logInData(); at the top, but have your function logInData() { ... } created down below.
I think what you want to do it put the whole function in an include file at the top like:
include ('includes/header.php');
include ('includes/logInFunction.php');
You then want to call logInData(); down in the body.
Another issue is your function puts data in an array and echos data. If you are going to have $error= logInData(); at the top of your page try moving this out of your function and into your body where you want to output the errors.
if(count($error) > 0)
{
foreach($error as $key => $value)
{
echo "ERROR: $value<br />\n";
}
}
When the user submits a form, the PHP will check to see if the $post was empty, if so, it will set an $error_message variable; thus database INSERT query will not execute. I then attempt to show the error message further on in the code, however it will not display. I have been trying to figure this out for hours and I still cannot find the solution. The funny thing is, this used to work, however I must have implemented something in this file which is preventing the code to execute correctly.
Why is my error message not echoing to the screen (last few lines of code show attempt to echo the error_message)?
<?php require("inc/db.php"); ?>
<?php include("inc/functions.php"); ?>
<?php include ("inc/ChromePhp.php"); ?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set("html_errors", 1);
session_start();
if(!isset($_GET['id'])) {
header("Location: ?id=".getUserId($_SESSION['U_Email']));
}
if(isset($_SESSION["U_Email"])) {
$usersData = getUserInfo($_GET['id']);
$postCount = getPostCount($_GET['id']);
} else {
header('Location: login.php');
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
$post = trim(filter_input(INPUT_POST,"user_post",FILTER_SANITIZE_SPECIAL_CHARS));
if($post == "") {
$error_message = "Please enter something before submitting";
}
if(!isset($error_message)) {
$post = $db->real_escape_string($post);
$postStore = $db->query("INSERT INTO `Post`(P_Body, P_Dateadded, User_U_ID) VALUES ('{$post}', NOW(), '{$_SESSION['U_ID']}' )");
}
}
$dashNav = true;
$cap = true;
$pageTitle = 'Profile';
$name = $usersData['U_Forename'] . " " . $usersData['U_Surname'];
$gender = $usersData['U_Gender'];
$bio = $usersData['U_Biography'];
$team = $usersData['U_Team'];
$city = $usersData['U_City'];
include("inc/header.php");
?>
<?php if(userExists($_GET['id'])) { ?>
<section>
<div class="wrapper">
<?php
if($_SESSION['U_ID'] != $_GET['id']) {
$testFollow = "SELECT `Following`.F_ID, `Following`.U_ID FROM `Following`
WHERE U_ID = '{$_SESSION['U_ID']}' AND F_ID = '{$_GET['id']}'";
$testFollowResult = $db->query($testFollow);
if ($testFollowResult->num_rows > 0) {
echo "<button class='lift' href='#'>Unfollow Driver</button>";
} else {
echo "<button class='lift' href='#'>Follow Driver</button>";
}
}
?>
<?php if (isset($error_message)) {
// This code will not echo!
echo "<h2>".$error_message."</h2>";
}
?>
</div>
<div class="section-b">
<div class="grid">
<div class="row">
<div class="col-wd-12">
<div class="col">
<form id="share" name="share" action="profile.php" method="post">
<textarea id="post" name="user_post" placeholder="What's happening?"> </textarea>
<span id="errorpost" class="error">You must input something something before sending</span>
<?php
echo "<div class='g-recaptcha' data- sitekey='6LfNTB0TAAAAAKEw9zfnFzvGCXF9MuYTkdB144x1
'></div>"; ?>
<button onclick="return postCheckValidate();" type="submit">Share</button>
</form>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
i have this form code.
<form action="save_profile.php" method="post">
<table>
<tr><td>First Name:</td><td><input type="text" name="fname" value="<?php echo $fname;?>"></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lname" value="<?php echo $lname;?>"></td></tr>
<tr><td>Mail ID:</td><td><input type="text" name="mail" value="<?php echo $mail;?>"></td></tr>
<tr><td>Contact NO:</td><td><input type="text" name="contact" value="<?php echo $contact;?>"></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Save Profile"></td></tr>
</table>
</form>
and my save_profile.php file has this code.
<?php
session_start();
require('config.php');
function is_valid_fname($fname,$lname,$contact)
{
if (empty($fname)) {
?>
<center><strong><font color="red">First Name is required.</font></strong></center>
<?php
return false;
}
if ( !preg_match ("/^[a-zA-Z\s]+$/",$fname)) {
?>
<center><strong><font color="red">First Name Only Contain Letters.</font></strong></center>
<?php
return false;
}
if (strlen($fname)>20) {
?>
<center><strong><font color="red">First Name must be less than 20 Letters.</font></strong></center>
<?php
return false;
}
if (empty($lname)) {
?>
<center><strong><font color="red">Last Name is required.</font></strong></center>
<?php
return false;
}
if ( !preg_match ("/^[a-zA-Z\s]+$/",$lname)) {
?>
<center><strong><font color="red">Last Name Only Contain Letters.</font></strong></center>
<?php
return false;
}
if (strlen($lname)>20) {
?>
<center><strong><font color="red">Last Name must be less than 20 Letters.</font></strong></center>
<?php
return false;
}
if (empty($contact)) {
?>
<center><strong><font color="red">Contact is required.</font></strong></center>
<?php
return false;
}
if ( !preg_match ("/^[0-9\s]+$/",$contact)) {
?>
<center><strong><font color="red">Contact Only Contain Numbers.</font></strong></center>
<?php
return false;
}
if (strlen($contact)>15) {
?>
<center><strong><font color="red">Contact must be less than 20 Digits.</font></strong></center>
<?php
return false;
}
else{
return true;
}
}
function is_valid_email($mail)
{
if (empty($mail)) {
?>
<center><strong><font color="red">Email is required.</font></strong></center>
<?php
return false;
} else {
$email = test_input($mail);
// check if e-mail address is well-formed
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
?>
<center><strong><font color="red">Invalid Email Format.</font></strong></center>
<?php
return false;
}
// now check if the mail is already registered
$slquery = "SELECT 1 FROM user_tbl WHERE user_mail = '".$mail."'";
$selectresult = mysql_query($slquery);
if(mysql_num_rows($selectresult)>1) {
?>
<center><strong><font color="red">This Email Is Already Exits.</font></strong></center>
<?php
return false;
}
// now returns the true- means you can proceed with this mail
return true;
}
}
if (isset($_POST['submit'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$mail = $_POST['mail'];
$contact = $_POST['contact'];
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (is_valid_email($mail) && is_valid_fname($fname,$lname,$contact))
{
$query="UPDATE user_tbl SET user_fname='".$fname."' AND user_lname='".$lname."' AND user_mail='".$mail."' AND user_contact='".$contact."' WHERE user_id='".$_SESSION['uid']."'";
$result = mysql_query($query);
if ($result) {
header('location:profile.php');
}
}
else{
?>
<center><strong><font color="red">Error Updating User.</font></strong></center>
<?php
}
}
?>
my problem is after displaying data in form when i change form data and when i submit form it will always update my user_fname=0...when i change other field then my other fields remain same and set user_fname=0.please help me...
Please use comma(,) in stead of and
$query="UPDATE user_tbl SET user_fname='".$fname."', user_lname='".$lname."', user_mail='".$mail."', user_contact='".$contact."' WHERE user_id='".$_SESSION['uid']."'";
"SELECT `1` FROM `user_tbl` WHERE `user_mail` = '".$mail."'";
"UPDATE `user_tbl` SET `user_fname`='".$fname."' AND `user_lname`='".$lname."'AND
`user_mail`='".$mail."' AND `user_contact`='".$contact."' WHERE
`user_id`='".$_SESSION['uid']."'";
You forgot the grave accent.Now check is that still working or not .
I am developing a website with User registration and login ,after completing the page configuration ,i tried to register it worked perfectly and later next day i tried to register but the page is not loading ,after filling in the data and if i click submit ,it reloads the same register page with no effect ,how to solve this problem
SQL Query Processing code: (class.newuser.php)
enter code here
class User
{
public $user_active = 0;
private $clean_email;
public $status = false;
private $clean_password;
private $clean_username;
private $unclean_username;
public $sql_failure = false;
public $mail_failure = false;
public $email_taken = false;
public $username_taken = false;
public $activation_token = 0;
function __construct($user,$pass,$email)
{
//Used for display only
$this->unclean_username = $user;
//Sanitize
$this->clean_email = sanitize($email);
$this->clean_password = trim($pass);
$this->clean_username = sanitize($user);
if(usernameExists($this->clean_username))
{
$this->username_taken = true;
}
else if(emailExists($this->clean_email))
{
$this->email_taken = true;
}
else
{
//No problems have been found.
$this->status = true;
}
}
public function userPieAddUser()
{
global $db,$emailActivation,$websiteUrl,$db_table_prefix;
//Prevent this function being called if there were construction errors
if($this->status)
{
//Construct a secure hash for the plain text password
$secure_pass = generateHash($this->clean_password);
//Construct a unique activation token
$this->activation_token = generateactivationtoken();
//Do we need to send out an activation email?
if($emailActivation)
{
//User must activate their account first
$this->user_active = 0;
$mail = new userPieMail();
//Build the activation message
$activation_message = lang("ACTIVATION_MESSAGE",array("{$websiteUrl}/",$this->activation_token));
//Define more if you want to build larger structures
$hooks = array(
"searchStrs" => array("#ACTIVATION-MESSAGE","#ACTIVATION-KEY","#USERNAME#"),
"subjectStrs" => array($activation_message,$this->activation_token,$this->unclean_username)
);
/* Build the template - Optional, you can just use the sendMail function
Instead to pass a message. */
if(!$mail->newTemplateMsg("new-registration.txt",$hooks))
{
$this->mail_failure = true;
}
else
{
//Send the mail. Specify users email here and subject.
//SendMail can have a third parementer for message if you do not wish to build a template.
if(!$mail->sendMail($this->clean_email,"New User"))
{
$this->mail_failure = true;
}
}
}
else
{
//Instant account activation
$this->user_active = 1;
}
if(!$this->mail_failure)
{
//Insert the user into the database providing no errors have been found.
$sql = "INSERT INTO `".$db_table_prefix."users` (
`username`,
`username_clean`,
`password`,
`email`,
`activationtoken`,
`last_activation_request`,
`LostpasswordRequest`,
`active`,
`group_id`,
`sign_up_date`,
`last_sign_in`
)
VALUES (
'".$db->sql_escape($this->unclean_username)."',
'".$db->sql_escape($this->clean_username)."',
'".$secure_pass."',
'".$db->sql_escape($this->clean_email)."',
'".$this->activation_token."',
'".time()."',
'0',
'".$this->user_active."',
'1',
'".time()."',
'0'
)";
return $db->sql_query($sql);
}
}
}
}
?>
HTML register.php
enter code here
<?php
require_once("models/config.php");
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: index.php"); die(); }
?>
<?php
//Forms posted
if(!empty($_POST))
{
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
//Perform some validation
//Feel free to edit / change as required
if(minMaxRange(5,25,$username))
{
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT",array(5,25));
}
if(minMaxRange(8,50,$password) && minMaxRange(8,50,$confirm_pass))
{
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT",array(8,50));
}
else if($password != $confirm_pass)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if(!isValidemail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
//End data validation
if(count($errors) == 0)
{
//Construct a user object
$user = new User($username,$password,$email);
//Checking this flag tells us whether there were any errors such as possible data duplication occured
if(!$user->status)
{
if($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE",array($username));
if($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE",array($email));
}
else
{
if(!$user->userPieAddUser())
{
if($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if(count($errors) == 0)
{
if($emailActivation)
{
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
} else {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
}
}
?>
<!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>Registration | <?php echo $websiteName; ?> </title>
<?php require_once("head_inc.php"); ?>
</head>
<body>
<div class="modal-ish">
<div class="modal-header">
<h2>Sign Up</h2>
</div>
<div class="modal-body">
<div id="success">
<p><?php echo $message ?></p>
</div>
<div id="regbox">
<form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>
<label>Username:</label>
<input type="text" name="username" />
</p>
<p>
<label>Password:</label>
<input type="password" name="password" />
</p>
<p>
<label>Re-type Password:</label>
<input type="password" name="passwordc" />
</p>
<p>
<label>Email:</label>
<input type="text" name="email" />
</p>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" name="new" id="newfeedform" value="Register" />
</div>
</form>
</div>
<div class="clear"></div>
<p style="margin-top:30px; text-align:center;">Login / Forgot Password? / Home Page</p>
</body>
</html>
Its all due to div tags:
2 divisions closed within the form tag but they are opened outside the form tag.
So try by enclosing the whole form within one div(regbox) Including submit.
And make sure that no div is closed within form tag which is opened outside form tag.