database insertion signup failed - php

<?php require 'header.inc.php';
require 'connect.inc.php'; ?>
<?php
$reg = #$_POST['reg'];
$fn = "";
$ln = "";
$un = "";
$em = "";
$pswd = "";
$d = "";
$u_check = "";
$fn = strip_tags(#$_POST['fname']);
$ln = strip_tags(#$_POST['lname']);
$un = strip_tags(#$_POST['uname']);
$em = strip_tags(#$_POST['email']);
$pswd = strip_tags(#$_POST[ 'pass']);
$d = date('Y-m-d');
if($reg){
if($fn&&$ln&&$un&&$em&&$pswd){
$u_check = mysql_query("SELECT uname FROM users WHERE uname='$un'");
$check = mysql_num_rows($u_check);
if ($check == 0) {
if (strlen($un)<4||strlen($fn)<4||strlen($ln)<4) {
if (strlen($un)>20||strlen($fn)>20||strlen($ln)>20) {
echo "<div id=\"errormsg\"> <p>username/first name/last should not be over 20 characters</p> </div>";
}else {
$pswd = md5($pswd);
$query = mysql_query("INSERT INTO users VALUES ('','$un','$fn','$ln','$em','pass')");
die("welcome to vydoo");
}
}else {
echo "<div id=\"errormsg\"> <p>username/first name/last should not be under 4 characters</p> </div>";
}
}else {
echo "<div id=\"errormsg\"> <p>Username is allready taken</p> </div>";
}
}else {
echo "<div id=\"errormsg\"> <p>Please fill in all fields</p> </div>";
}
}
?>
<div class="content">
<div class="infos">
<p class="w">Sign Up and discover the great community</p>
<p class="s">Sign up in few steps , its free and unlimited</p>
</div>
<form class="form" method="POST">
<input class="Firstname" type="text" name="fname" placeholder="Fisrt name">
<input class="Lastname" type="text" name="lname" placeholder="Last name">
<input class="username" type="text" name="uname" placeholder="Usename">
<input class="email" type="email" name="email" placeholder="Email">
<input class="pass" type="password" name="pass" placeholder="Password">
<input class="submit" type="submit" name="reg" valueenter code here="Sign In">
</form>
i does not send information to database ! where is the problem please , i corrected every signle mistake in there and i cant find where is the problem , i have allready asked this question but with a different code , now i dont find my wrong code

Related

My code doesn't insert into the database because of my form validation

Each time I use the method below to insert my form into the database, it doesn't do anything...
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post" class="form-horizontal">
<div class="form-group">
<label for="first_name" class="col-sm-4 control-label" >First Name:</label>
<div class="col-sm-8">
<input type="text" name="first_name" class="form-control" id="first_name" value="<?= $first_name; ?>"/>
<span id="error-msg"><?= $first_name_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="last_name" class="col-sm-4 control-label">Last Name:</label>
<div class="col-sm-8">
<input type="text" name="last_name" class="form-control" maxlength="30" id="last_name" value="<?= $last_name; ?>"/>
<span id="error-msg"><?= $last_name_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="email_address" class="col-sm-8 control-label">Email Address:</label>
<div class="col-sm-8">
<input type="text" name="email_address" class="form-control" id="email_address" placeholder="abc#email.com" value="<?= $email_address; ?>"/>
<span id="error-msg"><?= $email_address_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="user_name" class="col-sm-4 control-label" >Username:</label>
<div class="col-sm-8">
<input type="text" name="username" class="form-control" maxlength="30" id="user_name" value="<?= $username; ?>"/>
<span id="error-msg"><?= $username_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="country" class="col-sm-4 control-label">Phone:</label>
<div class="col-sm-8">
<input type="tel" id="phone" name="phone" class="form-control" value="<?= $phone; ?>"/>
<span id="valid-msg" class="hide">► </span>
<span id="error-msg" class="hide"><?= $phone_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="pass_word" class="col-sm-4 control-label" >Password:</label>
<div class="col-sm-8">
<input type="password" name="password" class="form-control" maxlength="30" id="password" value="<?= $password; ?>"/>
<span id="error-msg"><?= $password_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="confirm_password" class="col-sm-4 control-label" >Confirm password:</label>
<div class="col-sm-8">
<input type="password" name="confirm_password" class="form-control" maxlength="30" id="confirm_password" value="<?= $confirm_password; ?>"/>
<span id="error-msg"><?= $confirm_password_error; ?></span>
</div>
</div>
<div class="col-sm-8 col-sm-push-3">
<input type="submit" name="submit" class="btn bg-success" value="Register" onClick="return confirm('Are you sure your details are correct?');" />
</div>
</form>
<?php
//define variables and set them to empty values
$first_name = $last_name = $country = $phone = $email_address = $username = $password = $confirm_password = "";
$first_name_error = $country_error = $last_name_error = $phone_error = $email_address_error = $username_error = $password_error = $confirm_password_error = "";
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
//form is submitted with post method
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["first_name"])){
$first_name_error = "<div class=''>First Name is required</div>";
}else{
$first_name = test_input($_POST["first_name"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^[a-zA-Z ]*$/",$first_name)){
$first_name_error = "<div class=''>Only letters and white space allowed</div>";
}
}
if(empty($_POST["last_name"])){
$last_name_error = "<div class=''>Last Name is required</div>";
}else{
$last_name = test_input($_POST["last_name"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^[a-zA-Z ]*$/",$last_name)){
$last_name_error = "<div class=''>Only letters and white space allowed</div>";
}
}
if(empty($_POST["email_address"])){
$email_address_error = "<div class=''>Email is required</div>";
}else{
$email_address = test_input($_POST["email_address"]);
// check if email address is well formed
if(!filter_var($email_address, FILTER_VALIDATE_EMAIL)){
$email_address_error = "<div class='btn bg-warning'>Invalid email format</div>";
}elseif($email_address = test_input($_POST["email_address"])){
$sql = "SELECT email_address FROM customers WHERE email_address = '$email_address'";
$mail = $database->query($sql);
if(mysqli_num_rows($mail) > 0){
$email_address_error = '<div class="">ERROR: Email already exists please use another email</div>';
}
}
}
if(empty($_POST["username"])){
$username_error = "<div class=''>Username is required</div>";
}else {
$username = test_input($_POST["username"]);
//check if username is atleast 7 characters
if(!preg_match("/^(?=.*?[a-z]).{7,}$/",$username)){
$username_error = "<div class=''>Username must be atleast 7 characters</div>";
}elseif($username = test_input($_POST["username"])){
$sql = "SELECT username FROM customers WHERE username = '$username'";
$user = $database->query($sql);
if(mysqli_num_rows($user) > 0){
$username_error = '<div class="">ERROR: Username already exists please use another username</div>';
}
}
}
if(empty($_POST["phone"])){
$phone_error = "<div class=''>Phone is required</div>";
}else {
$phone = test_input($_POST["phone"]);
}
if(empty($_POST["password"])){
$password_error = "<div class=''>Password is required</div>";
}else{
$password = test_input($_POST["password"]);
//check if password is atleast 7 characters
if(!preg_match("/^(?=.*?[a-z]).{7,}$/",$password)){
$password_error = "<div class=''>Password must be atleast 7 characters</div>";
}
}
if(empty($_POST["confirm_password"])){
$confirm_password_error = "<div class=''>Alternate password is required</div>";
}else{
$confirm_password = test_input($_POST["confirm_password"]);
//check if cpassword is atleast 8 characters
if(!preg_match("/^(?=.*?[a-z]).{7,}$/",$confirm_password)){
$confirm_password_error = "<div class=''>Password must be atleast 7 characters</div>";
}else{
if($_POST['confirm_password'] != $password){
$confirm_password_error = "<div class=''>Password does not match!!!</div>";
}
}
}
if($first_name_error = "" and $last_name_error = "" and $mobile_number_error = "" and $email_address_error = "" and $username_error = "" and $password_error = "" and $confirm_password_error = ""){
$str = '1234567890asdf';
$str = str_shuffle($str);
$str = substr($str, 0, 10);
$token = 'vfjhvbkebecbjDRCWVJEcbkrvlnke24tir7c_zdvbejw968';
$token = str_shuffle($token);
$token = substr($token, 0, 10);
$user = new Customer_reg();
$password = sha1($password);
$user->customer_id = $str;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->email_address = $email_address;
$user->username = $username;
$user->password = $password;
$user->mobile_number = $phone;
$user->created_at = $timestamp;
$user->updated_at = $timestamp;
$user->emailConfirm = 0;
$user->token = $token;
$user->str = $str;
if($user->save()){
$mail = new Mail();
$mail->email_address = $email_address;
$mail->token = $str;
$mail->send_verification();
$session->message('<div class="btn bg-success">Account created sucessfully please verify your email.</div>');
redirect_to('login.php');
}
}
if(empty($_POST["message"])){
$message = "";
} else{
$message = test_input($_POST["message"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = htmlentities($data);
return $data;
}
?>
I realized my code has a bug from
if($first_name_error = "" and $last_name_error = "" and $mobile_number_error = "" and $email_address_error = "" and $username_error = "" and $password_error = "" and $confirm_password_error = "")
Please, how do I modify this? All my functions and every other code works perfectly okay apart from the above.
First of all, you should be using '==' here, not '=', and "&&" not "and".
I.e. change this:
if($first_name_error = "" and $last_name_error = "" and $mobile_number_error = "" and $email_address_error = "" and $username_error = "" and $password_error = "" and $confirm_password_error = "") { }
to this:
if($first_name_error == "" && $last_name_error == "" && $mobile_number_error == "" && $email_address_error == "" && $username_error == "" && $password_error == "" && $confirm_password_error == "") { }
Ensure you define $mobile_number_error and try executing your codes again and see.

Data ain't changed after submitted to mysql

i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.

How do i style PHP validations

This my first time using PHP validation and my validations are working perfectly.
How do i style the validation, do i select the echo function or do i have to change my validation code to be able to style it. I have tried using a span and echoing out a error function and changing the echo's to the error function e.g $emailErr but not luck, the validations does not work. any suggestions?
HTML
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required><!--<span class="error"><!--<?php //echo $c_emailErr; ?></span>-->
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required><!--<span class="error"><1--<?php //echo $c_pass1Err; ?></span>-->
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><!--<?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
PHP
<?php
if (isset($_POST['submit'])) {
$reg_errors = array();
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$emailErr = $pass1Err = $pass2Err = "";
// $c_email = $c_pass1 = $c_pass2 = "";
// Remove all illegal characters from email
// $c_email = filter_var($c_email, FILTER_SANITIZE_EMAIL);
//Checking the email address
if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
echo("<b> This is a valid email address </b>");
} else {
echo("<b> Email is not a valid email address</b>");
}
if (strlen($c_pass1) <= '8') {
echo "<b>Your Password Must Contain At Least 8 Characters!</br>";
//check passwords
}elseif ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
?>
say you had tag for text and you have the code
<?
echo '<t>this is some text';
?>
to add styles all you simply have to do is style the "t" tag like so in css
t{
font-size:3px;
background-color:red;
// other styles
}

PHP- Form Validation Errors

This is my first time validating, I am having the hardest time have spent endless hours on this already. I have a registration form that needs to be validated, i have tried 2 scripts for this. The script that works best can be seen below: however every time I try to echo the error message to display under my text field i receive the following error messages:
Notice: Undefined variable: c_email in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 161
Notice: Undefined variable: c_emailErr in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 163
Notice: Undefined variable: c_pass1Err in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 169
C_emailErr and c_pass1Err are both defined.
any help would be appreciated.
HTML
<section class="container">
<form id="myform " class="Form" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" accept-charset="utf-8">
<!--<div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value="<?= $c_email ?>" required >
<br>
<span class="error"><?php echo $c_emailErr; ?></span>
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="<?= $c_pass1 ?>" placeholder="Password" maxlength="30" required>
<br>
<span class="error"><?php echo $c_pass1Err; ?></span>
<br>
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
<?php
?>
</form>
</section>
PHP
<?php
if (isset($_POST['submit'])) {
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
//Checking the email address
if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
echo ("<b id='email'> This is a valid email address </b>");
} else {
echo ("<b id='email'> Email is not a valid email address</b>");
}
if (strlen($c_pass1) <= '8') {
echo "<b>Your Password Must Contain At Least 8 Characters!</br>";
//check passwords
} elseif ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
?>
You are defining those variables, but you are defining them inside of an if block.. Move them outside of the if block.
<?php
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
if (isset($_POST['submit'])) {
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];

i am trying to make a user login in php

i am trying to make the user show when i click browse in phpmyadmin in localhost. i created a table called test. i am trying, when you sign up, it shows the user in the database and signs him or her up, but it does not using this code:
hoping.php:
<?php
$reg = #$_users['reg'];
$fn = "";
$ln = "";
$un = "";
$em = "";
$em2 = "";
$pswd = "";
$pswd2 = "";
$d = "";
$u_check = "";
$fn = strip_tags(#$_test['fname']);
$ln = strip_tags(#$_test['lname']);
$un = strip_tags(#$_test['username']);
$em = strip_tags(#$_users['email']);
$em2 = strip_tags(#$_users['email2']);
$pswd = strip_tags(#$_users['password']);
$pswd2 = strip_tags(#$_users['password2']);
$d = date("Y-m-d");
if ($reg) {
if ($em == $em2) {
$u_check = mysql_query("SELECT username FROM users WEHRE username='$un'");
$check = mysql_num_rows($u_check);
if ($check == 0) {
if ($fn && $ln && $un && $em && $em2 && $pswd && $pswd2) {
if ($pswd == $pswd2) {
if (strlen($un) > 25 || strlen($fn) > 25 || strlen($ln) > 25) {
echo "The maximum limit for username/first name/last name is 25 characters!";
} else {
if (strlen($pswd) > 30 || strlen($pswd) < 5) {
echo "Your password must be between 5 and 30 characters long!";
} else {
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$query = mysql_query("INSERT INTO users VALUES ('', '$un', '$fn', '$ln','$em', '$pswd', '$d','0')");
die("<h2>Welcome to communicate</h2>Login to your account to get started ...");
}
}
} else {
echo "Your passwords don't match!";
}
} else {
echo "Please fill in all of the fields";
}
} else {
echo "Username already taken ...";
}
} else {
echo "Your E-mails don't match!";
}
}
if (isset($_users["user_login"]) && isset($_users["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_users["user_login"]);
$password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_users["password _login"]);
}
?>
<div style="width: 800px; margin: 0px auto 0px auto;">
<table>
<tr>
<td width="60%" valign="top">
<h2>Already a member? Sign in below!</h2>
<form action="hoping.php" method="users">
<input type="text" name="username" size="25" placeholder="Username"/><br /><br />
<input type="text" name="Password2" size="25" placeholder="Password (again)"/><br /><br />
<input type="submit" name="reg" value="Sign Up!">
</form>
<td>
<td width="40%">
<h2>Sign Up Below!</h2>
<form action="hoping.php" method="users">
<input type="text" name="fname" size="25" placeholder="First Name" />
<p />
<input type="text" name="lname" size="25" placeholder="Last Name"/><br /><br />
<input type="text" name="username" size="25" placeholder="username"/><br /><br />
<input type="text" name="email" size="25" placeholder="Email Address"/><br /><br />
<input type="text" name="email2" size="25" placeholder="Email Address (again)"/><br /><br />
<input type="text" name="password" size="25" placeholder="Password"/><br /><br />
<input type="text" name="Password2" size="25" placeholder="Password (again)"/><br /><br />
<input type="submit" name="reg" value="Sign Up!">
</td>
</tr>
</table>
<?php include ("./connect.inc.php");
connect.inc.php
<?php
mysql_connect("localhost", "root", "") or die("Couldnt conocet to server");
mysql_select_db("test") or die("Could'nt select DB");
?>
Ok so here's the improved script. Please make sure you read all the comments and correct stuff where needed as this is NOT ready-to-use code!
Change your connect.inc.php to (please make sure you fill in all the nessesary information):
<?php
$dbhost = ""; //MySQL host (usually: localhost)
$dbuser = ""; //MySQL user
$dbpass = ""; //MySQL password
$dbname = ""; //MySQL database name
$pdo = new PDO("mysql:host=".$dbhost.";dbname=". $dbname, $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Change hoping.php to:
<?php
require "connect.inc.php";
/*
Using md5 to encrypt a password is not secure.
I've written a much more secure function for password encryption.
However this requires your database to have enough room for it.
For example: `password` VARCHAR(128) NOT NULL
If you need to alter your database to make the room, please
execute this command in phpMyAdmin (change password to whatever
the column name is in your users table):
ALTER TABLE `users` MODIFY COLUMN `password` VARCHAR(128);
If your database has the room for this, please set the following
variable to true. Otherwise leave it false to keep using md5.
*/
$secureCrypt = false;
if(isset($_POST['login'])){
$sql = "SELECT * FROM users WHERE username = :user";
$pre = $pdo->prepare($sql);
$pre->bindValue(":user", $_POST['Username']);
if($pre->execute()){
$data = $pre->fetch();
if($secureCrypt){
//Please correct 'column_name_here'.
//I was unable to do this for you because I lacked the column name
//where the passwords are stored.
if(crypt($_POST['Password'], $data['column_name_here']) == $data['column_name_here']){
echo "You have succesfully logged in!<br />";
} else {
echo "Invalid password!<br />";
}
} else {
if(md5($_POST['Password']) == $data['column_name_here']){
echo "You have succesfully logged in!<br />";
} else {
echo "Invalid password!<br />";
}
}
} else {
echo "\nMySQL returned error:\n";
print_r($pdo->errorInfo());
}
}
if(isset($_POST['register'])){
$error = false;
$error_text = "";
//Check names for illegal characters
// Allows A-Z, a-z, underscore( _ ), dots( . ), spaces and dashes( - )
function nameRegex($var){
if(!preg_match("/^[a-zA-Z_\. \-]+$/i", $var)){
return true;
} else {
return false;
}
}
//Check names for illegal characters
// Allows A-Z, a-z, underscore( _ ), dots( . ) and dashes( - )
function userRegex($var){
if(!preg_match("/^[0-9a-zA-Z_\-]+$/i", $var)){
return true;
} else {
return false;
}
}
//Check for valid mail address
function mailFilter($var){
if(filter_var($var, FILTER_VALIDATE_EMAIL) === false){
return true;
} else {
return false;
}
}
//Check if 2 values match
function matchValues($var1, $var2){
if($var1 != $var2){
return true;
} else {
return false;
}
}
//Check if username already exists
function checkUser($user){
$sql = "SELECT username FROM users WHERE username = :user";
$pre = $pdo->prepare($sql);
$pre->bindValue(":user",$user);
if($pre->execute()){
$count = $pre->rowCount();
if($count > 0){
return true;
} else {
return false;
}
} else {
echo "\nMySQL returned error:\n";
print_r($pdo->errorInfo());
}
}
//Check for correct size
function checkSize($var, $size){
if(strlen($var) > $size){
return true;
} else {
return false;
}
}
//Securely encrypt user passwords
function cryptPass($pass, $rounds = 9){
$salt = "";
$saltChars = array_merge(range('A','Z'), range('a','z'), range(0,9));
for($i=0;$i<22;$i++){
$salt .= $saltChars[array_rand($saltChars)];
}
return crypt($pass, sprintf('$2y$%02d$', $rounds) . $salt);
}
if(nameRegex($_POST['fname'])){
$error = true;
$error_text .= "Your First Name contains illegal characters!<br />";
}
if(nameRegex($_POST['lname'])){
$error = true;
$error_text .= "Your Last Name contains illegal characters!<br />";
}
if(userRegex($_POST['username'])){
$error = true;
$error_text .= "Your Username contains illegal characters!<br />";
}
if(mailFilter($_POST['email'])){
$error = true;
$error_text .= "Your Email Address does not appear to be valid!<br />";
}
if(mailFilter($_POST['email2'])){
$error = true;
$error_text .= "Your 2nd Email Address does not appear to be valid!<br />";
}
if(matchValues($_POST['email'], $_POST['email2'])){
$error = true;
$error_text .= "It appears both Email Addresses did not match!<br />";
}
if(matchValues($_POST['password'], $_POST['password2'])){
$error = true;
$error_text .= "It appears both Passwords did not match!<br />";
}
if(checkUser($_POST['username'])){
$error = true;
$error_text .= "The Username is already taken by another user!<br />";
}
if(checkSize($_POST['fname'], 25)){
$error = true;
$error_text .= "The First Name contains to many characters!<br />";
}
if(checkSize($_POST['lname'], 50)){
$error = true;
$error_text .= "The Last Name contains to many characters!<br />";
}
if(checkSize($_POST['username'], 16)){
$error = true;
$error_text .= "The Username contains to many characters!<br />";
}
if(checkSize($_POST['username'], 125)){
$error = true;
$error_text .= "The Email address contains to many characters!<br />";
}
if(!$error){
if($secureCrypt){
$hashPass = cryptPass($_POST['password']);
} else {
$hashPass = md5($_POST['password']);
}
$sql = "INSERT INTO users VALUES ('',':username',':fname',':lname',':email',':password',':date','0')";
$pre = $pdo->prepare($sql);
$pre->bindValue(":username",$_POST['username']);
$pre->bindValue(":fname",$_POST['fname']);
$pre->bindValue(":lname",$_POST['lname']);
$pre->bindValue(":email",$_POST['email']);
$pre->bindValue(":password",$_POST['password']);
$pre->bindValue(":date",date("Y-m-d"));
if($pre->execute()){
echo "You are succesfully registered. Welcome!";
} else {
echo "\nMySQL returned error:\n";
print_r($pdo->errorInfo());
}
} else {
echo "There are some problems with your registration.<br />";
echo "Please correct the following errors:<br /><br />";
echo $error_text;
echo "<br />";
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login Page</title>
<style>
#div1 {
width: 800px;
margin: 0px auto 0px auto;
}
#td1 {
width: 60%;
vertical-align: top;
}
#td2 {
width: 40%;
}
</style>
</head>
<body>
<div id="div1">
<table>
<tr>
<td id="td1">
<h2>Already a member? Sign in below!</h2>
<form action="hoping.php" method="post" id="user_login" accept-charset="utf-8">
<input type="text" name="username" size="25" placeholder="Username"/><br /><br />
<input type="password" name="Password" size="25" placeholder="Password"/><br /><br />
<input type="submit" name="login" value="Login!">
</form>
</td>
<td id="td2">
<h2>Sign Up Below!</h2>
<form action="hoping.php" method="post" id="user_register" accept-charset="utf-8">
<input type="text" name="fname" size="25" placeholder="First Name" value="<?php echo $_POST['fname'] ?>" /><br /><br />
<input type="text" name="lname" size="25" placeholder="Last Name" value="<?php echo $_POST['lname'] ?>" /><br /><br />
<input type="text" name="username" size="25" placeholder="username" value="<?php echo $_POST['username'] ?>" /><br /><br />
<input type="text" name="email" size="25" placeholder="Email Address" value="<?php echo $_POST['email'] ?>" /><br /><br />
<input type="text" name="email2" size="25" placeholder="Email Address (again)" value="<?php echo $_POST['email2'] ?>" /><br /><br />
<input type="text" name="password" size="25" placeholder="Password"/><br /><br />
<input type="text" name="password2" size="25" placeholder="Password (again)"/><br /><br />
<input type="submit" name="register" value="Sign Up!">
</form>
</td>
</tr>
</table>
</div>
</body>
</html>

Categories