multiple message using SESSION - php

I am working on a small project where I need to validate (server side) a form. With the following code it works well to show the messages "There is A problem" or "There is NO problem". I want now to show the messages like "The name is missing " when the name is missing or "The first name is not valid" when it is not. If many errors occurred, it would show multiple message. Every message must be shown in the same page as the form. I do not know if my explanations are clear.
<?php
echo $_SESSION["errorMsg"];
session_unset("errorMsg");
?>
<form method="post" action="test1.php">
<table class="contactInformation">
<tbody>
<tr>
<td>
<label for="">Nom</label>
</td>
<td>
<input type="text" name="lastName"/>
</td>
</tr>
<tr>
<td>
<label for="">Prénom</label>
</td>
<td>
<input type="text" name="firstName"/>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Envoyer la commande">
</form>
<?php
if (!empty($_POST["lastName"])) {
$lastName = trim($_POST["lastName"]);
if (strlen($lastName) < 2 || 50 < strlen($lastName)) {
$errors = "The name is not valid";
}
}
else {
$errors = "The name is missing";
}
if (!empty($_POST["firstName"])) {
$firstName = trim($_POST["firstName"]);
if (strlen($firstName) < 2 || 50 < strlen($firstName)) {
$errors = "The firstname is not valid";
}
}
else {
$errors = "the firstname is missing";
}
if ($errors != "") {
$_SESSION["errorMsg"] = "There is A problem";
header("Location: test2.php");
exit();
}
else {
$_SESSION["errorMsg"] = "There is NO problem";
header("Location: test2.php");
exit();
}
?>

If you are displaying all errors at one place only, then solution can be:
<?php
$errors = '';
if (!empty($_POST["lastName"])) {
$lastName = trim($_POST["lastName"]);
if (strlen($lastName) < 2 || 50 < strlen($lastName)) {
$errors .= "-The name is not valid. <br/>";
}
}
else {
$errors .= "-The name is missing. <br/>";
}
if (!empty($_POST["firstName"])) {
$firstName = trim($_POST["firstName"]);
if (strlen($firstName) < 2 || 50 < strlen($firstName)) {
$errors .= "-The firstname is not valid. <br/>";
}
}
else {
$errors .= "-the firstname is missing. <br/>";
}
if ($errors != "") {
$_SESSION["errorMsg"] = "There is A problem : <br/>".$errors;
header("Location: test2.php");
exit();
}
else {
$_SESSION["errorMsg"] = "There is NO problem";
header("Location: test2.php");
exit();
}
?>
Otherwise, you can be take errors in array:
<?php
$errors = array();
if (!empty($_POST["lastName"])) {
$lastName = trim($_POST["lastName"]);
if (strlen($lastName) < 2 || 50 < strlen($lastName)) {
$errors['lastname'] = "The name is not valid";
}
}
else {
$errors['lastname'] = "The name is missing";
}
if (!empty($_POST["firstName"])) {
$firstName = trim($_POST["firstName"]);
if (strlen($firstName) < 2 || 50 < strlen($firstName)) {
$errors['firstname'] = "The firstname is not valid";
}
}
else {
$errors['firstname'] = "the firstname is missing";
}
if ($errors != "") {
$_SESSION["errorMsg"]["status"] = "There is A problem";
$_SESSION["errorMsg"]["details"] = $errors;
header("Location: test2.php");
exit();
}
else {
$_SESSION["errorMsg"]["status"] = "There is NO problem";
header("Location: test2.php");
exit();
}
?>

Related

PHP form is displayed but doesn't do anything besides clear itself when submitted

My HTML form is displayed by the else portion of my if statement. The if portion checks to see if the form was posted to SELF then should echo the form inputs. Instead, the form clears itself and echoes nothing.
<html>
<head>
<script>
function myFunction()
{
alert("I am an alert box!"); // this is the message in ""
}
</script>
</head>
<body>
<?php
//Display output once form submitted
if(isset($_POST['submit'])) {
//debug
echo '<script>myfunction()</script>';
// define variables and set to empty values
$firstname = 'test';
$middlename = 'test';
$lastname = 'test';
$email = 'test';
$phone = 'test';
$dd214 = 'test';
$description = 'test';
$firstnameErr = 'test';
$middlenameErr = 'test';
$lastnameErr = 'test';
$emailErr = 'test';
$phoneErr = 'test';
$dd214Err = 'test';
$descriptionErr = 'test';
if (empty($_POST["FIRSTNAME"])) {
$firstnameErr = "First name is required";
}
else {
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstnameErr = "Only letters and white space allowed";
}
else {
$firstname = test_input($_POST["FIRSTNAME"]);
}
}
if (empty($_POST["MIDDLENAME"])) {
$middlenameErr = "Middle name is required";
}
else {
if (!preg_match("/^[a-zA-Z ]*$/",$middlename)) {
$middlenameErr = "Only letters and white space allowed";
}
else {
$middlename = test_input($_POST["MIDDLENAME"]);
}
}
if (empty($_POST["LASTNAME"])) {
$lastnameErr = "Last name is required";
}
else {
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastnameErr = "Only letters and white space allowed";
}
else {
$lastname = test_input($_POST["LASTNAME"]);
}
}
if (empty($_POST["EMAILADDRESS"])) {
$emailErr = "Email is required";
}
else {
if (!filter_var($_POST["EMAILADDRESS"], FILTER_VALIDATE_EMAIL)){
$emailErr = "Please enter a valid email address";
}
else {
$email = test_input($_POST["EMAILADDRESS"]);
}
}
if (empty($_POST["PHONENUMBER"])) {
$phoneErr = "Phone number is required";
}
else {
if(!filter_var($_POST["PHONENUMBER"], FILTER_SANITIZE_NUMBER_INT)) {
$phoneErr = "Please enter a valid phone number";
}
else{
if ((strlen($_POST['PHONENUMBER']) >= 10) && (strlen($_POST['PHONENUMBER']) <= 14)){
$phone = test_input($_POST["PHONENUMBER"]);
}
else {
$phoneErr = "Please enter a valid phone number";
}
}
}
if (empty($_POST["DD214"])) {
$dd214Err = "DD214 is required";
}
else {
if (!get_mime_type($dd214)) {
$dd214Err = "Please ensure your DD214 is a jpeg or pdf file.";
}
else {
$dd214 = test_input($_POST["DD214"]);
}
}
if (empty($_POST["DESCRIPTION"])) {
$descriptionErr = "Description is required";
}
else {
$description = test_input($_POST["DESCRIPTION"]);
}
echo "Results:\r\n";
echo $firstname;
echo $middlename;
echo $lastname;
echo $email;
echo $phone;
echo $dd214;
echo $description;
echo $firstnameErr;
echo $middlenameErr;
echo $lastnameErr;
echo $emailErr;
echo $phoneErr;
echo $dd214Err;
echo $descriptionErr;
}
else {
echo "<form name='contactform' method='post' autocomplete='ON'>";
echo "Please enter your full name:";
echo "<br>";
echo "<table>";
echo "<tr>";
echo "<td>First*";
echo "<br>";
echo "<input type='text' name='FIRSTNAME' required maxlength='30' autofocus>\r\n";
echo "</td>";
echo "<td>Middle*";
echo "<br>";
echo "<input type='text' name='MIDDLENAME' required maxlength='30'>\r\n";
echo "<td>Last*";
echo "<br>";
echo "<input type='text' name='LASTNAME' required maxlength='20'>\r\n";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "<br>";
echo "Email address:";
echo "<br>";
echo "<input type='email' name='EMAILADDRESS' required pattern='^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'>\r\n";
echo "<br><br>";
echo "Phone number:";
echo "<br>";
echo "<input type='text' name='PHONENUMBER' required pattern='^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$' maxlength='14'>\r\n";
echo "<br><br>";
echo "Please upload a PDF or JPEG of your DD214:";
echo "<br>";
echo "<input type='file' name='DD214' accept='.pdf, .jpeg, .jpg' style='color:firebrick;'>";
echo "<br><br>";
echo "Brief description of your legal issue (1000 char max):";
echo "<br>";
echo "<input type='text' name='DESCRIPTION' required maxlength='1000' style:'width:40%;height:15%;'>\r\n";
echo "<br>";
echo "<p>Notice: Do not send confidential information using this form. Use of this form does not create an attorney-client relationship and therefore is not considered privileged and confidential information. Until an attorney-client relationship is created by agreement of the parties, anything submitted could be subjected to court-ordered disclosure.</p>";
echo "<input type='submit' value='submit' style='color: #DDDDDD;'>";
echo "</form>";
//Helper Functions
function get_mime_type($file) {
$mtype = false;
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mtype = finfo_file($finfo, $file);
finfo_close($finfo);
} elseif (function_exists('mime_content_type')) {
$mtype = mime_content_type($file);
}
if ($mtype == application/pdf || $mtype == image/jpeg)
{
return true;
}
else {
return false;
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>
</body>
</html>
I think the else portion must be working, because it displays the form HTML that's echoed if POST has not occurred. What I can't figure out is why the echoes showing the POSTed form fields don't appear. Ultimately this will be a contact form, but I need to at least get it working for some purposes before I finish that portion.
you have to add the name attribute to the sumbit button
echo "<input type='submit' name='submit' value='submit' style='color: #DDDDDD;'>";
When a form is submitted to the server, the data from the form is included in an HTTP request. The data is packaged as a series of name-value pairs. The name for each name-value pair is the name attribute of each input, and the value is the user-entered (or pre-specified) value. Without the name attribute, an element cannot provide its value to the server on form submission.
Read more: https://html.com/attributes/input-name/#ixzz5y9XVUvy4

I have an undefined variable in my PHP

I am very new to PHP and have been attempting to integrate with mysqli. Apparently on line 19 of my code the variable shown is undefined but as far as I can tell I defined it.
Here is the code. I've look around but I can't really find something to isolate this.
<?php
include("connect.php");
$error = "";
if(isset($_POST['submit']))
{
$characterName = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
}
if(strlen($fname) < 3)
{
$error = "Character name is too short";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error = "Please enter a valid email address";
}
else if(strlen($password) < 8)
{
$error = "Password must be more than 8 characters";
}
else if($password === $passwordConfirm)
{
$error = "Password does not match";
}
else if($image = "")
{
$error = "Please upload an Avatar";
}
else
{
$error = "You have successfully registered";
}
?>
Form Code:
<form method="post" action="index.php" enctype="multipart/form-data">
<label>Character Name:</label><br />
<input type="text" name="fname" /><br /><br />
<label>Email:</label><br />
<input type="text" name="email" /> <br /><br />
<label>Password:</label><br />
<input type="password" name="password" /><br /><br />
<label>Reenter Password:</label><br />
<input type="password" name="passwordConfirm" /><br /><br />
<label>Send us an Avatar:</label><br />
<input type="file" name="image" /><br /><br />
<input type="submit" name="submit" value="submit" />
</form>
if(strlen($fname) < 3) {
$error = "Character name is too short";
}
Here you have the error, $fname is not defined. What you there meaning is $_POST['fname'];. Which you stored in $characterName so change it to:
if(strlen($characterName) < 3){
$error = "Character name is too short";
}
Anyway, cause you define your variables only if isset($_POST['submit']), the lines below will fail if it is not set. Here is a example how it would work.
$_POST['submit'] is only defined if you call it with post parameters (formular, ajax..), so if you directly open the php file it wont work. I added a few comments to make it clear.
<?php
include("connect.php");
$error = "";
if(isset($_POST['submit'])) {
//If this block of variable declaration failed it wouldn´t define the variables
$characterName = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
//So we led Php only check the variables if a submit is provided
if(strlen($characterName) < 3) {
$error = "Character name is too short";
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Please enter a valid email address";
} else if(strlen($password) < 8) {
$error = "Password must be more than 8 characters";
} else if($password === $passwordConfirm) {
$error = "Password does not match";
} else if($image = "") {
$error = "Please upload an Avatar";
} else {
$error = "You have successfully registered";
}
} else {
//If there is no submit we land here
$error = "No data provided";
}
?>
if submit is not posted then only you receive undefined variables error. In order to avoid those errors. You just change your code like this
if(isset($_POST['submit']))
{
$characterName = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
}
else
{
$error ="Your submit is not posted.";
exit(); //Without it would again trigger the undefined variables.
}

Form doesn't working properly

If all inputs are filled, everything works just fine. But if I check just checkbox, the form let me register, no matter I didn't fill all the inputs.
Also if add var_dump to the bottom of the page ( when just checkbox is checked) it says "boolean false " Please help...
<?php
$page_title = 'Registracija'; // Definiše title i h1
$folder = 'registration-db';
if (!file_exists($folder)) {
mkdir($folder, 0777, true);`enter code here`
}
$fajl = $folder . '/registrovani_korisnici.txt';
// Citanje podataka
if (file_exists($fajl)) {
$podaci = file_get_contents($fajl);
$registracija = explode("\n", rtrim($podaci)); //Vracanje података iz baze
}
$errors = false;
//Obrada forme i provera podataka
if (!empty($_POST)) { //ako nije prazna promenljiva
//Provera da li su podaci unešeni
if (empty($_POST['user_name'])) { //radi
$errors[] = 'Niste upisali ime i prezime!<br>';
}
if (empty($_POST['user_email'])) { //radi
$errors[] = 'Niste uneli E-mail!<br>';
}
if (filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL) === false) {// Izbacio !empty($_POST['user_email']) &&
$errors[] = 'Nije validna email adresa!<br>';
}
if (empty($_POST['user_password'])) { //radi
$errors[] = 'Niste uneli lozinku!<br>';
}
if (strlen($_POST[]) <= 5) { //radi
$errors[] = 'Lozinka mora da ima više od 5 karaktera!<br>';
}
if (empty($_POST['user_password2'])) { //radi
$errors[] = 'Niste potvrdili lozinku!<br>';
}
if ($_POST['user_password'] !== $_POST['user_password2']) {
$errors[] = 'Lozinka mora da bude ista u oba pokušaja!';
}
if (empty($_POST['day']) || empty($_POST['month']) || empty($_POST['year'])) { //radi
$errors[] = 'Niste uneli ispravan datum!<br>';
}
if (empty($_POST['check'])) { //radi
$errors[] = 'Niste prihvatili uslove korišćenja!<br>';
}
/*if (date('Y') - $_POST['year'] < 15) {
$errors[] = 'Nemate dovoljno godina, da biste se registrovali!<br>';
}*/ //Problem kada se ne definiše vrednost $_POST['year']!!!!!
else {
// Data forwarding
extract($_POST);
// Name
// Skidanje tagova - Zbog bezbednosti!!!
$user_name = strip_tags($user_name);
//Pretvaranje u mala slova
$user_name = strtolower($user_name);
//Pretvaranje prvih slova u velika (Ime Prezime)
$user_name = ucwords($user_name);
// Čišćenje Email-a
$user_email = strip_tags($user_email);
//Čišćenje Lozinke
$user_password = strip_tags($user_password);
//Čišćenje Lozinke2
$user_password2 = strip_tags($user_password2);
/*html_entity_decode();
htmlentities();*/
$podaci .= $user_name . '#!$!#' . $user_email . '#!$!#' . $user_password . '#!$!#' . $user_password2 . '#!$!#' . $day . '.' . $month . '.' . $year . '#!$!#' . PHP_EOL;
//Zapisivanje u fajl
file_put_contents($fajl, $podaci);
header('Location: registracija.php?sent=1');
}
}
?>
<?php include 'inc/header.php'; //include header?>
<!-- Prikazivanje greške-->
<?php if ($errors !== false) : ?>
<p>GREŠKA: </p>
<?php foreach ($errors as $error) : ?>
<p><?php echo $error; ?></p>
<?php endforeach; ?>
<?php endif; ?>
<?php if (isset($_GET['sent']) && $_GET['sent'] == 1): ?>
<h2>Uspešno ste registrovani! Hvala.</h2>
<?php else : ?>
<!-- Form -->
<form action="" method="post">
<p>
<input type="text" name="user_name" placeholder="Ime i prezime">
</p>
<p>
<input type="email" name="user_email" placeholder="E-mail">
</p>
<p>
<input type="password" name="user_password" placeholder="Lozinka">
</p>
<p>
<input type="password" name="user_password2" placeholder="Ponovite lozinku">
</p>
<h2>Datum rodjenja</h2>
<select name="day">
<option selected disabled>Dan</option>
<?php for ($i = 1; $i <= 31; $i++) : ?>
<option> <?php echo $i; ?> </option>
<?php endfor; ?>
</select>
<select name="month">
<option selected disabled>Mesec</option>
<?php for ($i = 1; $i <= 12; $i++) : ?>
<option> <?php echo $i; ?> </option>
<?php endfor; ?>
</select>
<select name="year">
<option selected disabled>Godina</option>
<?php
$start = date("Y");
$end = date("Y") - 100;
?>
<?php for ($i = $start; $i >= $end; $i--) : ?>
<option> <?php echo $i; ?> </option>
<?php endfor; ?>
</select>
<br>
<br>
<input type="checkbox" name="check"> Prihvatam uslove korišćenja
<p>
<button>Registrujte se</button>
</p>
</form>
<?php endif; ?>
<!-- Form END -->
<?php include 'inc/footer.php'; //include footer?>
First of all, you might want to turn you if statements into a if - else if - else chain. In your situation, if last if statement returns false, your former validations become void.
if (empty($_POST['day'])) {
//Validation
}
else if (empty($_POST['year'])) {
//Validation
}
else if (empty($_POST['check'])) {
//Validation
}
// Other validations
else {
}
Also, you should add a value to your checkbox like this:
<input type="checkbox" name="check" value="1" />
This way, if it's checked, it will post a value.
In your current situation, even if checkbox is checked, you don't send any value and your last if statement evaluates to false.
EDIT:
To display all missing fields at once, you just change your else statement into another if-else statements like this:
if (empty($_POST['user_name'])) {
$errors[] = 'Niste upisali ime i prezime!<br>';
}
if (empty($_POST['check'])) {
$errors[] = 'Niste prihvatili uslove korišćenja!<br>';
}
//Other validations
if($errors) {
//Show errors
}
else{
// Data forwarding
// Same as your former else statement
}
It's a small logical error. Your else block is only associated with your last if block. As a result, else will be entered if the last if block is not executed.
If $_POST['check'] is not empty that is if the condition inside the lastif block` returns false then the else will be entered and registration gets completed.
What could you do to get around this?
Use a flag. Declare a variable as $c=1;. We will change the value of this variable to 0 if any if block is entered.
$c=1;
if (empty($_POST['user_name'])) { //radi
$errors[] = 'Niste upisali ime i prezime!<br>';
$c=0;
}
if (empty($_POST['user_email'])) { //radi
$errors[] = 'Niste uneli E-mail!<br>';
$c=0;
}
if (filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL) === false) {// Izbacio !empty($_POST['user_email']) &&
$errors[] = 'Nije validna email adresa!<br>';
$c=0;
}
if (empty($_POST['user_password'])) { //radi
$errors[] = 'Niste uneli lozinku!<br>';
$c=0;
}
if (strlen($_POST[]) <= 5) { //radi
$errors[] = 'Lozinka mora da ima više od 5 karaktera!<br>';
$c=0;
}
if (empty($_POST['user_password2'])) { //radi
$errors[] = 'Niste potvrdili lozinku!<br>';
$c=0;
}
$if ($_POST['user_password'] !== $_POST['user_password2']) {
$errors[] = 'Lozinka mora da bude ista u oba pokušaja!';
$c=0;
}
$if (empty($_POST['day']) || empty($_POST['month']) || empty($_POST['year'])) { //radi
$errors[] = 'Niste uneli ispravan datum!<br>';
$c=0;
}
$if (empty($_POST['check'])) { //radi
$errors[] = 'Niste prihvatili uslove korišćenja!<br>';
$c=0;
}
elseif ($c==1)
{
//CODE
}
else if block will only be entered if $c==1 is true.
You could also use if-elseif-else ladder.
OR:
You can use the required attribute in each input tag to force the users to fill that particular field before submitting.
eg:
<input type="email" name="user_email" Placeholder="Email" required>
Add the required attribute in each input tag to stop the form from getting submitted if a field is not entered.
For example, in the above case, the form wouldn't get submitted if email-id is not entered.

Not displaying Error Message

i am a newbie in this php. i am trying to make some validation for my form which will show the error msg if it exploits my validation rules.
my connection file.
<?php
$con = mysql_connect("localhost","root","") or die('could not connect the server: '. mysql_error());
mysql_select_db("interview",$con);
?>
my validate.php file
<?php
require_once('connect.php');
$realnameErr = $nickErr = $passwordErr = $emailErr = "";
$realname = $nick = $password = $email = "";
?>
my form
<form name='v2' id='login' method='post' action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Login</legend>
<label for='realname' >Real Name*:</label>
<input type='text' name='realname' id='realname' maxlength="50" value="<?php echo $realname;?>" /></br>
<span class="error"><?php echo $realnameErr;?></span>
<br>
<label for='nick' >Nick*:</label>
<input type='text' name='nick' id='nick' maxlength="50" value="<?php echo $nick;?>" /></br>
<span class="error"><?php echo $nickErr;?></span>
<br>
<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" /></br>
<span class="error"><?php echo $passwordErr;?></span>
<br>
<label for='email' >Email*:</label>
<input type='text' name='email' id='email' maxlength="50" value="<?php echo $email;?>"/></br>
</fieldset>
<input type='submit' name='submit' value='submit' />
</form>
validation begins here
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['submit'])) {
if (empty($_POST["realname"]))
{
$realnameErr = "Name is required";
}
else
{
$realname=test_input($_POST["realname"]);
if(!preg_match("/^[a-zA-z ]*$/",$realname))
{
$realnameErr = "only letters and white space allowed";
}}
if(empty($_POST["nick"]))
{
$nickErr = "Nick is required";
}
else {
$nick=($_POST["nick"]);
}
if(empty($_POST["password"]))
{
$passwordErr = "password is required";
}
else {
$password=($_POST["password"]);
}
if(empty($_POST["email"]))
{
$emailErr = "email is required";
}
else {
$email=test_input($_POST["email"]);
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}}
checking then inserting
if((!$realnameErr) && (!$nickErr) && (!$passwordErr) && (!$emailErr)) {
$query="INSERT INTO `main`"."(realname,nick,password,email)". "VALUES". "('$realname','$nick',SHA('$password'),'$email')";
$res=mysql_query($query);
echo '<p>Your account has been Successfully created,You are now ready to login. </p>';
}
}}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
You need to have your working Script before you display your form. Because at the moment, the time you output <span class="error"><?php echo $nickErr;?></span> the variable $nickErr is still empty and therefore does not display anything.
Try this:
// Init
$errors = array();
// Validate Post Data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['submit'])) {
if (empty($_POST["realname"])) {
$errors[] = "Name is required";
} else {
$realname = test_input($_POST["realname"]);
if (!preg_match("/^[a-zA-z ]*$/", $realname)) {
$errors[] = "only letters and white space allowed";
}
}
if (empty($_POST["nick"])) {
$errors[] = "Nick is required";
} else {
$nick = ($_POST["nick"]);
}
if (empty($_POST["password"])) {
$errors[] = "password is required";
} else {
$password = ($_POST["password"]);
}
if (empty($_POST["email"])) {
$errors[] = "email is required";
} else {
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$errors[] = "Invalid email format";
}
}
}
}
// If there is any error
if (sizeof($errors))
{
// display it
echo '<div>Following error(s) occured:<br /><br />'. implode('<br />', $errors) .'</div>';
}
else
{
// proceed with db insert here
}

Live check doesn't work using PDO

I am using JQuery to check if username is in use, however I have some issues. It is always stuck of "Searching". Image below shows exactly what the issue is.
Register.JS:
$(document).ready(function(){
$('#username').keyup(function() {
var username = $(this).val();
$('#usernameCheck').text('Searching...');
if (username === '') {
$('#usernameCheck').text('');
}else {
$.post('usernamecheck', { username:username }, function(data) {
$('#usernameCheck').text(data);
});
}
});
});
Register.php:
<html>
<head>
<title>Register</title>
<link rel='stylesheet' type='text/css' href='styles.css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="JS/register.js"></script>
</head>
</html>
<?php
echo '<form action="register.php?action=registerCheck" method="post" name="formOne">
<br/><input type="text" id="username" placeholder="Username" maxlength="50" title="Maximum 50 charcters or less."><span id="usernameCheck"></span><br/>
<br/><input type="password" name="passwordOne" placeholder="Password" maxlength="60" title="Maximum 60 charcters or less."><br/>
<br/><input type="password" name="passwordTwo" placeholder="Retype Password" maxlength="60" title="Must be the same as the password field above this."><br/>
<br/><input type="text" name="email" placeholder="Email Address" title="Must be correct in-case admins wish to contact you."><br/>
<br/><textarea disabled rows="1" cols="4" name="defSpamCheck">'.$spamCheck.'</textarea><br/>
<br/><textarea rows="1" cols="30" name="userSpamCheck" placeholder="Enter the 4 digit code above." title="Needed to check for bots."></textarea><br/>
<br/><input type="submit" value="Register" onclick="return validate()">
</form>';
}
function registerCheck() {
global $PDO;
// All the validations
if (!isset($_POST['username']) || empty($_POST['username'])) {
echo '<br/>';
echo '<p class="error">You missed out the usernane field.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['passwordOne']) || empty ($_POST['passwordOne'])) {
echo '<br/>';
echo '<p class="error">You missed out the password field.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['passwordTwo']) || empty ($_POST['passwordTwo'])) {
echo '<br/>';
echo '<p class="error">You missed out the second password field.</p>';
echo 'Back';
endPage();
} else if ($_POST['passwordOne'] != $_POST['passwordTwo']) {
echo '<br/>';
echo '<p class="error">Passwords do not match.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['email']) || empty ($_POST['email'])) {
echo '<br/>';
echo '<p class="error">You missed out the email field.</p>';
echo 'Back';
endPage();
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo '<br/>';
echo '<p class="error">Email not valid.</p>';
echo 'Back';
endPage();
} else if (!isset ($_POST['userSpamCheck']) || empty ($_POST['userSpamCheck'])) {
echo '<br/>';
echo '<p class="error">You missed out the spam check field.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['username']) > 50) {
echo '<br/>';
echo '<p class="error">Username has to be 50 characters or less.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['passwordOne']) && strlen($_POST['passwordTwo']) > 60) {
echo '<br/>';
echo '<p class="error">Password has to be 60 characters or less.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['username']) < 5) {
echo '<br/>';
echo '<p class="error">Username has to be greater than 5 characters.</p>';
echo 'Back';
endPage();
} else if (strlen($_POST['passwordOne']) && strlen($_POST['passwordTwo']) < 5) {
echo '<br/>';
echo '<p class="error">Password has to be greater than 5 characters</p>';
echo 'Back';
endPage();
} else {
$username = htmlspecialchars($_POST['username']);
// Replace all these with $replace
$sChars = array ("<", ">", "(", ")", "*", "&", "#", ":");
$replace = ' ';
// Trim to remove any blank spaces
trim(str_replace($sChars, $replace, $username));
$password = sha1(htmlspecialchars($_POST['passwordOne']));
$email = htmlspecialchars($_POST['email']);
$stmtOne = $PDO->prepare("SELECT COUNT(`uID`) uUsername FROM `users` WHERE uUsername=? LIMIT 1");
$stmtOne->bindParam(1, $username, PDO::PARAM_INT);
$stmtOne->execute();
$result = $stmtOne->fetch(PDO::FETCH_ASSOC);
if ($result == 1) {
echo '<br/>';
echo '<p class="error">Username already in use, pick another one.</p>';
echo 'Back';
endPage();
}
$stmtTwo = $PDO->prepare("INSERT INTO `users` (uUsername, uPassword, uEmail) VALUES (?, ?, ?)");
if ($stmtTwo->execute(array($username, $password, $email))) {
echo '<br/>';
echo '<p class="norm">Account created! You can now log in.</p>';
header("Refresh:3; URL=login.php");
endPage();
} else {
echo '<br/>';
echo '<p class="error">We could not create your account, please try again later.</p>';
header("Refresh:3; URL=login.php");
endPage();
}
}
}
?>
usernamecheck.php:
<?php
include 'pdo.config.php';
include 'register.php';
global $username;
$stmtOne = $PDO->query("SELECT COUNT(*) uUsername FROM `users` WHERE uUsername='$username'");
$rows = $stmtOne->fetchALL();
$count = count($rows);
if ($count < 1) {
echo 'Username already in use, pick another one';
} else if ($count == 0) {
echo 'Username available';
}
?>
But it won't work, what am I doing wrong?
$count is the number of rows. Your query always returns exactly 1 row, since it's just returning a count. Also, both your if tests are checking if $count is 0 (I think you meant to write $count == 1 for the first one).
$stmtOne = $PDO->prepare("SELECT COUNT(*) uUsername FROM `users` WHERE uUsername = :username");
$stmtOne->exec(array('username' => $username));
$row = $stmtOne->fetch(PDO::FETCH_OBJ);
$count = $row->uUsername;
if ($count == 1) {
echo 'Username already in use, pick another one';
} else if ($count == 0) {
echo 'Username available';
}
Okay, so my code was right but I had a small but critical error.
$(document).ready(function(){
$('#username').keyup(function() {
var username = $(this).val();
$('#usernameCheck').text('Searching...');
if (username === '') {
$('#usernameCheck').text('');
}else {
$.post('usernamecheck', { username:username }, function(data) {
$('#usernameCheck').text(data);
});
}
});
});
Where it's looking for the file, I put "usernamecheck". It was mean't to be usernamecheck.php. I missed out the file extension.

Categories