Undefined variable in php registration from - php

Continuing from my previous post "PHP and MYSQL database connection and table creation only once", I created the registration form with the PHP code and server side validation. I’m getting some errors as stated below.
i.e. all errors are occurring at the place where i try to print the errors in their respected html class “”. I've made the html "span class" text bold for easy recognition. If their is anything extra solutions for better performance of the form please let me know...
List of errors:
Notice: Undefined variable: error_name in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_username in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_password in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_password2 in C:\wamp\www\18+\register.php
Notice: Undefined variable: error_email in C:\wamp\www\18+\register.php
Register.php
<?php
include ‘database.php';
session_start();
if (isset($_POST['submit'])) {
$error = " "; //Declare a null variable to store error messages
//validation for fullname
if (empty($_POST['fullname'])) {
$error_name = 'Enter Fullname...';
} else {
$fullname = mysql_real_escape_string(trim($_POST['fullname']));
}
//validation for username
if (empty($_POST['username'])){
$error_username = 'Enter Username...';
} else {
$username = mysql_real_escape_string(trim($_POST['username']));
}
//validation for password
if(empty($_POST['password'])){
$error_password = 'Please Enter Your Password...';
} else {
if (empty($_POST['password2'])) {
$error_password2 = 'Re-enter Your Password...';
} else {
if(($_POST['password'])!=($_POST['password2'])){
$error_password2 = 'Passwords Do not match...';
} else {
$confirm = mysql_real_escape_string(md5($_POST['password2']));
}
}
}
//validation for e-mail
if (empty($_POST['email'])) {
$error_email = 'Please Enter your Email ';
} else {
if (preg_match("//custom preg match characters", $_POST['e-mail'])) {
//regular expression for email validation
$email = mysql_real_escape_string($_POST['email']);
} else {
$error_email = 'Your E-mail Address is invalid ';
}
}
if (empty($error)) //send to Database if there's no error '
{
$query= "DB INSERT QUERY";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Failed to Register Your Account...!';
} else {
echo 'Account Registered Successfully...!';
}
}
mysqli_close($sql);//Close the DB Connection
}
?>
Index.php
<form action="register.php" method="post" id="user_registration">
<p id="head">Create Account</p>
<input type="text" id="fullname" name="fullname"/>
**<span class="error" id="fullname"><?php echo $error_name; ?></span>**
<input type="text" id="username" name="username"/>
<span id="availability_status"></span>
**<span class="error" id="username"><?php echo $error_username; ?></span>**
<input type="password" id="password" name="password"/>
**<span class="error" id="password"><?php echo $error_password; ?></span>**
<input type="password" id="password2" name="password2"/>
**<span class="error" id="divCheckPasswordMatch"><?php echo $error_password2;?></span>**
<input type="email" id="email" name="email"/>
**<span class="error" id="email"><?php echo $error_email; ?></span>**
<p class="submit">
<button type="submit"id="submit" name="submit" value="Register”>Register</button>
</p>
</form>

First of all You need to fix the quote at include ‘database.php'; to include 'database.php'; never use curly quote due to this all your code is being blocked.
Next You need to initialize all variable to null or simply ""
OR
You can check if the variable exist or not using isset() like if you want to print value of an variable $val then use this if(isset($val)) echo $val;
UPDATE
You can easily use an array to store errors:
simply use like
$error['name']='Enter Fullname...';
And to check if name error occurs use
if(isset($error['name'])){
//Its an error print error
}

you may need to define these variable on top of the page before using them in code something like this.
$error_name = '';
$error_username = '';
$error_password = '';
$error_password2 = '';
$error_email = '';

Put an else to your if (isset($_POST['submit']))
else { /* What if the user didn't click submit? Else is the answer */
$error_name="";
$error_username="";
$error_password="";
$error_password2="";
$error_email="";
}

The problem is, you are setting the messages only if certain conditions are true. Thus, these variables are not found if those conditions aren't true. To resolve this, use isset() when displaying the errors, e.g.
<?php echo isset($error_name)?$error_name:'' ; ?>
This means check if $error_name is set, if yes display it or display nothing.
Another thing (logically) is that your code is not actually checking for the errors. The $error remains an empty string and you are checking if it is empty which will always be true. You need to either store the errors as arrays or check if all the variables are empty.
Additional:
Can u tell me how to store the errors as arrays..plz
Try this:
<?php
include 'database.php';
session_start();
if (isset($_POST['submit'])) {
$error = array(); //<-- Declare array here
//validation for fullname
if (empty($_POST['fullname'])) {
$error['fullname'] = 'Enter Fullname...'; //<-- adding error into array
} else {
$fullname = mysql_real_escape_string(trim($_POST['fullname']));
}
//validation for username
if (empty($_POST['username'])){
$error['username'] = 'Enter Username...'; //<-- here too and so on..
} else {
$username = mysql_real_escape_string(trim($_POST['username']));
}
//validation for password
if(empty($_POST['password'])){
$error['password'] = 'Please Enter Your Password...';
} else {
if (empty($_POST['password2'])) {
$error['password2'] = 'Re-enter Your Password...';
} else {
if(($_POST['password'])!=($_POST['password2'])){
$error['password2'] = 'Passwords Do not match...';
} else {
$confirm = mysql_real_escape_string(md5($_POST['password2']));
}
}
}
//validation for e-mail
if (empty($_POST['email'])) {
$error['email'] = 'Please Enter your Email ';
} else {
if (preg_match("//custom preg match characters", $_POST['e-mail'])) {
//regular expression for email validation
$email = mysql_real_escape_string($_POST['email']);
} else {
$error['email'] = 'Your E-mail Address is invalid ';
}
}
if (!empty($error)) //send to Database if there's no error '
{
$query= "DB INSERT QUERY";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo 'Failed to Register Your Account...!';
} else {
echo 'Account Registered Successfully...!';
}
}
}
?>
Change your HTML to:
<form action="register.php" method="post" id="user_registration">
<p id="head">Create Account</p>
<input type="text" id="fullname" name="fullname"/>
<!-- checking if error message is set -->
**<span class="error" id="fullname"><?php echo isset($error['fullname'])?$error['fullname']:''; ?></span>**
<input type="text" id="username" name="username"/>
<span id="availability_status"></span>
**<span class="error" id="username"><?php echo isset($error['username'])?$error['username']:''; ?></span>**
<input type="password" id="password" name="password"/>
**<span class="error" id="password"><?php echo isset($error['password'])?$error['password']:''; ?></span>**
<input type="password" id="password2" name="password2"/>
**<span class="error" id="divCheckPasswordMatch"><?php echo isset($error['password2'])?$error['password2']:''; ?></span>**
<input type="email" id="email" name="email"/>
**<span class="error" id="email"><?php echo isset($error['email'])?$error['email']:''; ?></span>**
<p class="submit">
<button type="submit"id="submit" name="submit" value="Register">Register</button>
</p>
</form>
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Related

serverside validation for a sign in form

<form method="POST" onsubmit=" return formSubmit() " action="log-it-reports.php">
<div class="userimage">
<img class="userlogo" src="image/userlogo.png" alt="Picture- User Profile picture">
</div><br>
<div class="error" id= "errorMsg"></div><br>
<div class="error" id= "errorMsg1"></div>
<div class="field">
<label class="stafflabel"> Staff Name </label>
<input class="area" placeholder="staffmember or admin" onclick=" return userValidation()" onchange=" return userValidation()" id="staff" name="staffname" type="text" value="<?php echo $staffname;?>" >
</div> <br>
<div class="error" id= "errorMsg2"></div>
<div class="field">
<label class="passlabel"> Password </label>
<input class="area" placeholder="password" onclick=" return userValidation()" onchange=" return userValidation()" id="pass" name="password" type="password" value="<?php echo $password;?>" >
</div><br>
<div class="checkbox">
<input type="checkbox" class="remember-me">
<label class="remember" for="remember-me">Remember me </label>
<a class="pass-link" href="#"> Forgot password?</a>
</div><br><br><br>
<div class="field">
<input class="btn" type="submit" value="Sign in">
</div> <br>
<div class="account-link">
Didn't create an account yet? Create Account
</div>
</form>
I would like to validate a sign in form with predefined usernames (admin, staffmember) and passwords (heretohelp!456 , letmein!123) in the serverside using php, my approach to it is using if statements to check for the posted input , firstly, is this a good approach or there is a better way to do it ? secondly, i'm getting an error in my code that says : syntax error, unexpected 'else' (T_ELSE)
the brackets i have seem to match, the error shows in lines : 15, 32 of this snippet
<?php
$staffname = $_POST['staff'];
$password = $_POST['pass'];
$error = "";
// validating staff member:
if (isset($_POST['submit'])) {
if ($staffname == "staffmember") {
if ($password == "letmein!123") {
$error = "" ;
}
// redirect to the logs report page when successful
header("location: log-it-reports.php");
else {
$error = "* You have entered a wrong password!";
}
}
else {
$error = "You have entered a wrong staff name!";
}
}
// validating admin:
if (isset($_POST['submit'])) {
if ($staffname == "admin") {
if ($password == "heretohelp!456") {
$error = "" ;
}
// redirect to the logs report page when successful
header("location: update-log-reports.php");
else {
$error = "* You have entered a wrong password!";
}
}
else {
$error = "You have entered a wrong staff name!";
}
}
?>
I have fixed your code, so at least it is somewhat DRY and solves your syntax issues as pointed out by people in the comments.
Any decent PHP editor (use Vscode with the inteliphense plugin if you need something free) will show you syntax errors when you code and help you with PHP syntax. If you do use it, make sure you read the instructions and disable the default php plugins as per it's instructions.
<?php
// validating staff member:
$staffname = $_POST['staff'] ?? '';
$password = $_POST['pass'] ?? '';
$error = "";
if (isset($_POST['submit'])) {
if ($staffname == "staffmember") {
if ($password == "letmein!123") {
// redirect to the logs report page when successful
header("location: log-it-reports.php");
exit;
} else {
$error = "* You have entered a wrong password!";
}
} else if ($staffname == "admin") {
if ($password == "heretohelp!456") {
// redirect to the logs report page when successful
header("location: update-log-reports.php");
exit;
} else {
$error = "* You have entered a wrong password!";
}
} else {
$error = "You have entered a wrong staff name!";
}
// Maybe you want to actually send the error back to the browser if there was one?
echo "<p>$error</p>";
}
Pro tip: Your scripts should omit the php end tag ie. ?>. You never need it at the end of any PHP script, and having it included scripts can create output when you don't want or expect it. You only need to use the end tag when you have a script that has a mixture of PHP and html, and you are going in and out of PHP blocks. If PHP is the last thing in a script, then leave off the ?>
Something I added for your $_POST assignments: The Null coalescing operator. This handles the problem of someone submitting your form but leaving off either of the required fields.

Why this code isn't inserting data into database?

This is my registration form I am using both javascript and php for validating form, javascript code works well in showing validation error messages however somethings wrong with php code,when javascript is disabled php code should show form validation error messages by refrshing page on form submit,but no error messages appear and no data is inserted. On clicking submit, page is reloaded but even form does not appear.
<?php
error_reporting('E_ALL ^ E_NOTICE');
if(isset($_POST['reg'])){
$fn = ucfirst($_POST['fname']);
$ln = ucfirst($_POST['lname']);
$un = $_POST['username'];
$em = $_POST['email'];
$pswd = $_POST['password'];
$d= date("Y-m-d");
if (strlen($fn) < 2 || strlen($fn) > 15) {
$error = "First name must be 2 to 15 characters long";
}
elseif (strlen($ln) < 2 || strlen($ln) > 15) {
$error = "Last name must be 2 to 15 characters long";
}
elseif($em==""){
$error = "Email cannot be empty";
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format";
}
elseif($pswd==""){
$error = "Fill your password";
}
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
}
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
?>
<form action="" method="post">
<input type="text" name="fname" id="fn" placeholder="First Name"/><br />
<input type="text" name="lname" id="ln" placeholder="Last Name"/><br />
<input type="text" name="username" id="un" placeholder="Username" class="username" /><br />
<input type="email" name="email" id="em" placeholder="Email"/> <br />
<input type="password" name="password" id="pswd" placeholder="Password"/><br />
<input type="password" name="password2" id="pswd2" placeholder="Confirm Password"/><br />
<input type="submit" id="submit" name="reg" value="Create an Account">
<center><div id="er"><?php echo $error ?></div></center>
</form>
You should echo $error not $er
<center><div id="er"><?php echo $error; ?></div></center>
You are doing a mistake:
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
You should use 'username' instead of ':username'. like this:
$stmt->execute(array('username'=>$un,'firstname'=>$fn,'lastname'=>$ln,'email'=>$em,'password'=>$pswd));
There are a few inconsistencies in your code.
At the beginnig you assign $_POST['email'] to $em, but later you validate against a variable named $email, which doesn't exist at this point.
$em = $_POST['email'];
.
.
.
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format"; //should maybe be $error
}
Then there is the password-validation:
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
$pswd2 has never been defined in your code.
$stmt ist defined in the else-block of your validation, but you use it for getting the row-count after the validation. So, if any of your if-statements is true, this will cause an error.
It would be better if you change that part of your code to this:
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
After all it seems like you haven't error reporting activatet.

Redirecting page to a Success page if server validation is positive

I have a form with an action that is linked to the same PHP page contact.php. I have all the server side validation inside the form and it's all fine. It redirects the user to the same page with error messages echoed if needed while making the form STICKY (that is the main point of using the same page for errors).
What I would like is for there to be a success page redirect if the form was okay. I've read other posts on how to implement this, but I don't quite understand how to implement it in my code.
<?php
$fullname = $email = $reason = $contactbox = '';
$fullnameerr = $emailerr = $reasonerr = $contactboxerr = '';
if(data_post('submit')){
if(empty(data_post('firstname'))){
$fullnameerr = "Please enter a valid name";
}
else {
$fullname = clean_data(data_post('firstname'));
if (!preg_match("/^[a-zA-Z '']*$/", $fullname)){
$fullnameerr = "Please enter only alphabetical characters and white spaces";
}
}
if(empty(data_post('email'))){
$emailerr = "Please enter a valid e-mail";
}
else {
$email = clean_data(data_post('email'));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailerr = "Please enter a correct e-mail format (ex 'joe#cornell.edu')";
}
}
if(empty(data_post('reason'))){
$reasonerr = "Please select a reason for contact";
}
else{
$reason = clean_data(data_post('reason'));
}
if(empty(data_post('contacttext'))){
$contactboxerr = "Please elaborate on your reason";
}
else{
$contactbox = clean_data(data_post('contacttext'));
if(!preg_match("/^[\w\S\s]*$/", $contactbox )){
$contactboxerr = "Please enter only valid characters you would use in writing (ex 'abcABC123')";
}
if(strlen($contactbox) > 2000){
$contactboxerr = "Please enter a response with with a max of 2000 characters.";
}
}
}
function clean_data($field){
$field = trim($field);
$field = stripslashes($field);
return $field;
}
function data_post($param){
if (isset($_POST[$param])){
return $_POST[$param];
}
else{
return '';
}
}
?>
With this being the code for the form:
<div class="sidesection" id="survey">
<h3>Contact Form</h3>
<form action="contact.php" method="POST" novalidate>
<span class="required_asterick">* Is Required</span>
<fieldset>
<legend>Contact Us</legend>
<span class="required_asterick">* </span><label>Name:</label><span class="help" data-tooltip="Please enter a valid name (Ex. 'John Doe')"></span><br />
<input type="text" name="firstname" required pattern="[a-zA-Z '']+" maxlength="25" title="Enter only characters from (a-z) and (A-Z)" value="<?php echo "$fullname";?>"><span class="errormessage"><?php echo "$fullnameerr";?></span><br /><br />
<span class="required_asterick">* </span><label>Email:</label><span class="help" data-tooltip="Please enter a valid email with a max of 50 characters. (Ex. 'xxx#yyy.com')"></span><br />
<input type="email" name="email" required maxlength="50" value="<?php echo "$email";?>">
<span class="errormessage"><?php echo "$emailerr"; ?></span><br /><br />
<span class="required_asterick">* </span><label>Reason For Contact:</label>
<select name="reason" required>
<option value=""> </option>
<option value="general">General</option>
<option value="concern">Concern</option>
<option value="feedback">Feedback</option>
</select><span class="help" data-tooltip="Choose a topic for which you are contacting us so we can process your request faster. General is for any broad topics not listed. Concern is for any pressing matter you may have about the Ithaca Apple Harvest Festival. Feedback is for any suggestions or opinions you wish to share with us about our festivals. "></span><span class="errormessage"><?php echo "$reasonerr";?></span><br /> <br />
<span class="required_asterick">* </span><label>What Would You Like To Tell Us?</label><span class="help" data-tooltip="Use this section to write what you are contacting us for."></span><br />
<textarea name="contacttext" rows="7" cols="60" required><?php echo "$contactbox";?></textarea><span class="errormessage"><?php echo "$contactboxerr"; ?></span><br />
<input type="submit" value="Submit" name="submit">
</fieldset>
</form>
You can see I made the form sticky by adding echoes to errors, so I want to keep that if there are errors. However if it is successful, redirect to a success page.
Just check if you have no errors (i.e. your error variables are empty) and use header()
$fullname = $email = $reason = $contactbox = '';
$fullnameerr = $emailerr = $reasonerr = $contactboxerr = '';
if(data_post('submit')){
// your validations go here
// ......
if (empty($fullnameerr) && empty($emailerr) && empty($reasonerr) && empty($contactboxerr)) {
header('Location: success.php');
}
}
You don't have a control to check whether the validation passed or failed. As a suggestion user a boolean variable to indicate it:
if(data_post('submit')){
$valid=true;
if(empty(data_post('firstname'))){
$fullnameerr = "Please enter a valid name";
$valid=false;
}
if(empty(data_post('email'))){
$emailerr = "Please enter a valid e-mail";
$valid=false;
}
//other validations
if($valid){
//validation passed
header('Location: destination.php');
}
}
In addition to #Deimoks answer, you may need to call exit(); after calling the header() function. If you have any code after the header redirection, it could still be executed even you requested a redirection. exit() prevents that. Also, if you get the "headers already sent" error, look into output buffering.

PHP - Redisplay forms with valid values in fields and error messages where validation fails

I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

Echoing $_POST error on correct page

thanks for reading.
I have an issue getting an error to echo on the correct page after a form submit. When the form is submitted, it redirects to website.com/controllers/accountController.php. I would like it to refresh the current page, website.com/play.php?p=myaccount
Please note that the form is submitting, it is just printing the error on the redirected page instead of the page with the form.
Please take a look at my previous question (related, but different question altogether).
HTML form (myaccount.inc.php):
<div id="change-password">
<form class="clearfix" action="controllers/accountController.php" method="post">
<div><span class="he1">Change Password</span></div>
<div><label class="DEVON" for="password">Current Password:</label></div>
<input type="password" name="password" id="password" size="23" /><br />
<div><label class="DEVON" for="passwordnew1">New Password:</label></div>
<input type="password" name="passwordnew1" id="passwordnew1" size="23" /><br />
<div><label class="DEVON" for="passwordnew2">Confirm New Password:</label></div>
<input type="password" name="passwordnew2" id="passwordnew2" size="23" /><br />
<input type="submit" name="submit" value="Change Password" class="bt_changepass" />
</form>
</div>
PHP code (accountController.php):
<?php
// Checking whether the Password Change form has been submitted.
if(isset($_POST['submit'])=='Change Password')
{
echo "<br />";
// Get the data from the database.
$sql = $mysqli->query("SELECT * FROM ss_members WHERE usr = '".$_SESSION['usr']."' AND pass = '".md5($_POST['password'])."'");
$row = $sql->fetch_assoc();
// Will hold our errors
$err = array();
if($_POST['password'] == "" || $_POST['passwordnew1'] == "" || $_POST['passwordnew2'] == "")
{
$err[] = 'All the fields must be filled in!';
}
if(!$row['pass'] == md5($_POST['password']) && $_POST['passwordnew1'] != "" && $_POST['passwordnew2'] != "")
{
$err[] = 'Current password is not correct!';
}
if($_POST['passwordnew1'] <> $_POST['passwordnew2'])
{
$err[] = 'New passwords do not match!';
}
if(!count($err))
{
if($row['usr'])
{
// If everything is OK change password.
$stmt = $mysqli->prepare("UPDATE ss_members SET pass = md5(?) WHERE usr = {$_SESSION['usr']}");
$stmt->bind_param('s', $_POST['passwordnew1']);
$stmt->execute();
$stmt->close();
echo "Password has been sucessfully updated!<br />";
}
else
{
$err[]='Something broke!';
}
}
if($err)
{
// Save the error messages in the session.
foreach($err as $error)
{
echo $error . "<br />";
}
}
echo "<br />";
}
if(isset($_POST['submit'])=='Change Password') statment is wrong.
Because isset always return Boolean so your if won't execute ever.
OR
You can use it as
if(isset($_POST['submit']) && $_POST['submit'] =='Change Password')
if(isset($_POST['submit'])=='Change Password')
isset returns true of false when comparing it with the change password will return false
Regards.
if(isset($_POST['submit'])=='change Password')
this usage is not valid in php

Categories