Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
Sign in to follow this  
codeminer

form validation

Recommended Posts

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
/**
 * Note that the salt here is randomly generated.
 * Never use a static salt or one that is not randomly generated.
 *
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you
 */


// define variables and set to empty values
$usernameErr = $passwordErr = $firstnameErr = $emailErr = $genderErr = $websiteErr = "";
$username = $password = $firstname = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  
  if (empty($_POST["username"])) {
    $usernameErr = "UserName is required";
  } else {
    $username = test_input($_POST["username"]);
    
    if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
      $usernameErr = "Only letters and white space allowed"; 
    }
  }
  
   if (empty($_POST["password"])) {
    $passwordErr = "password word is required";
  } else {
    $password = test_input($_POST["password"]);
   
    if (!preg_match("/^(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{8,}/",$password)) {
      $passwordErr = "<br>Password must be a  mixure of <br>no# and letters containing <br>upper & lower case letters <br>at least 8 charecters<br>long"; 
    }
  }
  
    if (empty($_POST["firstname"])) {
    $firstnameErr = "FirstName is required";
  } else {
    $firstname = test_input($_POST["firstname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
      $firstnameErr = "Only letters and white space allowed"; 
    }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }
    
  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* Required Fields</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  
  Username:<br/> 
  <input type="text" name="username" value="<?php echo $username;?>">
  <span class="error">* <?php echo $usernameErr;?></span>
  <br><br>
  
  Password:<br/>  
  <input type="password" name="password" value="<?php echo $password;?>
?> ">
  <span class="error">* <?php echo $passwordErr;?></span>
  <br><br>
  
  
  
   Firstname:<br/>  
  <input type="text" name="firstname" value="<?php echo $firstname;?>">
  <span class="error">* <?php echo $firstnameErr;?></span>
  <br><br>
  
  E-mail:<br/>
  <input type="text" name="email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
 
  Website:<br/>
  <input type="text" name="website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
 
  Comment:<br/>
  <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
 
  Gender:<br/> 
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type = "reset" name = "reset"/> | 
  <input type="submit" name="submit" value="Submit">  
</form>

<h2><?php echo "WELLCOM!";?> <?php echo  $username;?></h2>

<?php 
$options = [
    'cost' => 9,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
 




echo "<br>";
echo $firstname;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;

?>
</body>
</html>

Hello  I need some advise on this   need to make sure this is correct . I took this form from w3shools a long time ago. I modified it with regular expressions went to php.net, pick the hash function manipulated the code a little bit just need to make sure it gonna fly thank you  in advance

Edited by codeminer

Share this post


Link to post
Share on other sites
8 hours ago, codeminer said:

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
/**
 * Note that the salt here is randomly generated.
 * Never use a static salt or one that is not randomly generated.
 *
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you
 */


// define variables and set to empty values
$usernameErr = $passwordErr = $firstnameErr = $emailErr = $genderErr = $websiteErr = "";
$username = $password = $firstname = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  
  if (empty($_POST["username"])) {
    $usernameErr = "UserName is required";
  } else {
    $username = test_input($_POST["username"]);
    
    if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
      $usernameErr = "Only letters and white space allowed"; 
    }
  }
  
   if (empty($_POST["password"])) {
    $passwordErr = "password word is required";
  } else {
    $password = test_input($_POST["password"]);
   
    if (!preg_match("/^(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{8,}/",$password)) {
      $passwordErr = "<br>Password must be a  mixure of <br>no# and letters containing <br>upper & lower case letters <br>at least 8 charecters<br>long"; 
    }
  }
  
    if (empty($_POST["firstname"])) {
    $firstnameErr = "FirstName is required";
  } else {
    $firstname = test_input($_POST["firstname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
      $firstnameErr = "Only letters and white space allowed"; 
    }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }
    
  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* Required Fields</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  
  Username:<br/> 
  <input type="text" name="username" value="<?php echo $username;?>">
  <span class="error">* <?php echo $usernameErr;?></span>
  <br><br>
  
  Password:<br/>  
  <input type="password" name="password" value="<?php echo $password;?>
?> ">
  <span class="error">* <?php echo $passwordErr;?></span>
  <br><br>
  
  
  
   Firstname:<br/>  
  <input type="text" name="firstname" value="<?php echo $firstname;?>">
  <span class="error">* <?php echo $firstnameErr;?></span>
  <br><br>
  
  E-mail:<br/>
  <input type="text" name="email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
 
  Website:<br/>
  <input type="text" name="website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
 
  Comment:<br/>
  <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
 
  Gender:<br/> 
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type = "reset" name = "reset"/> | 
  <input type="submit" name="submit" value="Submit">  
</form>

<h2><?php echo "WELLCOM!";?> <?php echo  $username;?></h2>

<?php 
//ok i found a article this needs to go in the insert script 
//this is just temporary out put it starting to make more sense
$options = [
    'cost' => 9,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
 




echo "<br>";
echo $firstname;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;

?>
</body>
</html>

Hello  I need some advise on this   need to make sure this is correct . I took this form from w3shools a long time ago. I modified it with regular expressions went to php.net, pick the hash function manipulated the code a little bit just need to make sure it gonna fly thank you  in advance

 

Share this post


Link to post
Share on other sites

sorry about this duplication im just not familiar with this editor I can't seem to locate the delete button

Share this post


Link to post
Share on other sites

Don't bother passing a salt to password_hash, let it generate one.  You're also not hashing the password they entered.

Other than that, I don't see the point of using htmlspecialchars in that test_input function, other than that the only thing you do with the form data is print it on the page.  If you're going to store it in a database you don't need to do that.  I also don't like the name of test_input, because it doesn't test anything.  The regular expression to validate the password is also a little bit overboard.  If you want to verify that it contains at least one uppercase letter, one lowercase, one digit, and is at least 8 characters total that's fine, you don't need a big regular expression to do that.  I hate it when some website rejects my complex password because it doesn't fit their arbitrary rules.

Share this post


Link to post
Share on other sites

I read your article that you put up a while back on form page mode very helpful and in depth in fact if I would have discovered sooner I wouldn't have post this

I know im just printing the hash out on the page .I Relies that it needs to be defined in the insert statement .what im trying to learn is how to put it  in the insert statement so that hashing of the password is accomplished in db . as far as the specialchars i never used them before i 'm trying to learn security  . here is my insert  file

<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
//____________________________________________	
	//trying to understand how to put this in the statement

	
	}else{

$options = [
    'cost' => 9,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$password = password_hash( "password"
,PASSWORD_BCRYPT, $options);

//_______________________________________					
$sql = "INSERT INTO users (username, password,email,website,comment,gender)
VALUES 
('$_POST[username]', 
 '$_POST[password]',
 '$_POST[email]',
 '$_POST[website]',
 '$_POST[comment]',
 '$_POST[gender]')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully, <a href = 'http://127.0.0.1/A'>Click here to continue</a>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();

 

Share this post


Link to post
Share on other sites

You hash the password prior to inserting in the database, but you add it to the database like any other value.  You wouldn't insert the plain text password from $_POST, you hash that password, get the hashed value, and then insert that hashed value into the database.  I would recommend that you learn how to use PDO for the database work though.  You need to use prepared statements when you're putting data in a query, and PDO is just easier and less complex for prepared statements than mysqli. 

http://php.net/manual/en/pdo.prepare.php 

http://php.net/manual/en/pdostatement.execute.php

 

Share this post


Link to post
Share on other sites

thank you for your expert advise. I managed to convert the password into the options array prior to inserting in to db using this code. It works!!!YA.THANK YOU

 //password
  
   if (empty($_POST["password"])) {
    $passwordErr = "password word is required";
  } else {
    $password = test_input($_POST["password"]);
   //changed the regular expression you can add up to 60 charecters
    if (!preg_match("/^(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{0,60}/",$password)) {
      $password_Err = "<br><P>Password must be a  mixure of no# and letters containing upper & lower case charecters</P>"; 
    }
  }
  
  // changed the name of password  to password_hash call the $options array  this is coverting the  password prior to getting to db it works
  
  
  $options = [
    'cost' => 9,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];

   $password = password_hash($password, PASSWORD_BCRYPT, array( '$options' ));
  

 

Edited by codeminer

Share this post


Link to post
Share on other sites

I thought this worked ,it doesn/'t hash the pass, It puts the hash in the data base  but it fires prematurely it causes the input field to be fill  before the user input is served . just need to keep pounding .hopefully ill get a break through, trial an error unfortunately mostly error

Share this post


Link to post
Share on other sites

ok change the whole file around ,found better  idea .This hashes the password  ,check the db if the username  is available, checks that the im format is true and checks the firstname against RE rules .returns error messages in the browser, i learned this from a video on youtube  


<?php
//This is the insert.php file

if (isset($_POST['submit'])){ 


	
	include_once 'db.php';

	$firstname = mysqli_real_escape_string($conn, $_POST['firstname']);
	$email = mysqli_real_escape_string($conn, $_POST['email']);
	$username = mysqli_real_escape_string($conn, $_POST['username']);
	$password = mysqli_real_escape_string($conn, $_POST['password']);
	

	//Error handlers
	//Check for empty fields
	if (empty($firstname) || empty($email) || empty($username) || empty($password)) {
		header("Location: ./index.php?Register=empty");
		exit();
	} else {
		//Check if input characters are valid
		if (!preg_match("/^[a-zA-Z]*$/", $firstname)) {
			header("Location: ./index.php?Register=NameInvalid");
			exit();
		} else {
			//Check if email is valid
			if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
				header("Location: ./index.php?Register=Invalid Email");
				exit();
				
			// Checks if username isnt being used by someone else	
			} else {
				$sql = "SELECT * FROM users WHERE username='$username'";
				$result = mysqli_query($conn, $sql);
				$resultCheck = mysqli_num_rows($result);

				if ($resultCheck > 0) {
					header("Location: ./index.php?Resiter=usertaken");
					exit();
				} else {
					//Hashing the password
					$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
					//Insert the user into the database
					$sql = "INSERT INTO users (firstname,email, 
	                username,password) VALUES ('$firstname','$email', '$username', '$hashedPassword');";
					mysqli_query($conn, $sql);
					header("Location: ./index.php?Register=success");
					exit();
				}
			}
		}
	}

} else {
	header("Location: ./index.php");
	exit();
}

 

Share this post


Link to post
Share on other sites

Again, I'd strongly recommend looking into prepared statements.  There's no reason to learn the wrong way to do something, then have to unlearn that and learn the right way.  Just start with the right way.  That means using prepared statements any time a query has data in it (or, for good practice, just every time).  Like I said, mysqli supports prepared statements, but they're easier with PDO.

Share this post


Link to post
Share on other sites

I agree my problem is that I started with mysqli I can due basic function like connect select insert I wanted to try to finish what I started once I get a grip on some of these basics I might have enough understanding to take the plunge with pdo I appreciate your input

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×