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
Related
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.
I am trying to implement a basic user registration RESTful api.
I have a html form registerform.html, deregisterform.html, users.php, register.php and deregister.php which are all pasted below.
When i visit the registerform.html in my browser, i can fill in the details and a POST request is received by the users.php script and a json response is echoed back showing the id number of the user thats just been added.
My problem is that when i use the deregister form, the users.php script should recive a DELETE request, but is actually getting a GET request. I've been looking for an answer to this problem but im not finding a solution.
registerform.html
<form action="users.php" method="POST">
Username: <input type="text" name="uname" /><br />
FirstName: <input type="text" name="fname" /><br />
Last Name: <input type="text" name="lname" /><br />
Date of Birth: <input type="date" name="dob" /><br />
Telephone: <input type="mob" name="tel" /><br />
Email: <input type="email" name="email1" /><br />
Confirm Email: <input type="email" name="email2" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name ="pass2" /><br />
<input type="submit" value="Register" name="sub" />
<br/>Already Registered? Login Here<br/>
</form>
deregisterform.html
<form action="users.php" method="DELETE">
Username: <input type="text" name="uname" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name ="pass2" /><br />
<input type="submit" value="Deregister" name="sub" />
</form>
register.php
<?php
if(isset($_POST['uname']) && isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['tel']) && isset($_POST['dob']) &&
isset($_POST['email1']) && isset($_POST['email2']) && isset($_POST['pass1']) && isset($_POST['pass2']))
{
//take values from http POST and trim whitespace
$uname = trim($_POST['uname']);
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$tel = trim($_POST['tel']);
$dob = trim($_POST['dob']);
$email1 = trim($_POST['email1']);
$email2 = trim($_POST['email2']);
$pass1 = trim($_POST['pass1']);
$pass2 = trim($_POST['pass2']);
//validate the data from the form
if($um->isNameFormatted($uname))
{
if(!$um->isUserExists($uname)) //does user already exist with this username?
{
if($um->isNameFormatted($fname)) //first name formatted correctly
{
if($um->isNameFormatted($lname)) //last name formatted correctly
{
if($um->isDOBFormatted($dob))
{
if($email1 == $email2)
{
if($pass1 == $pass2)
{
if($um->isPasswordClean($pass1))
{
if($um->isTelephoneVerified($tel))
{
//everything is OKAY --- PROCEED WITH ADDING USER
$user = $um->registerUser($uname,$fname,$lname,$dob,$tel,$email1,$pass1);
if(isset($user))///
{
//successful registration
$response["error"] = false;
$response["id"] = $user;
echo json_encode($response);
}
}
}
}
}
}
}
}
}
}
}?>
deregister.php
<?php
if(isset($_POST['uname']) && isset($_POST['pass1'] && isset($_POST['pass2'])
{
$uname = $_POST['uname'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($um->isUserExists($uname))
{
if($pass1 == $pass2)
{
if(true)//$um->isPasswordFor($uname, $pass))
{
$um->deregisterUser($uname, $pass1);
$response["error"] = false;
$response["text"] = "User removed!";
echo json_encode($response);
}
else
{
$response["error"] = true;
$response["text"] = "Wrong username and password combination!";
echo json_encode($response);
}
}
else
{
$response["error"] = true;
$response["text"] = "Passwords don't match!";
echo json_encode($response);
}
}
else
{
$response["error"] = true;
$response["text"] = "User(".$uname.") not in database!";
echo json_encode($response);
}
}?>
users.php
<?php
error_reporting( -1 );
require('userManagement.php');
$um = new UserManagement();
$response = array("error" => FALSE);
//check if user logged in and authenticated
if(true)
{
echo "user logged in.";
echo $httpVerb = trim(strtoupper($_SERVER['REQUEST_METHOD']));
switch($httpVerb)
{
case "GET":
$response["error"] = false;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
case "PUT":
$response["error"] = false;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
case "POST":
include('register.php');
break;
case "DELETE":
include('deregister.php');
break;
default:
echo "http verb ".$httpVerb." is not supported for this resource.";
$response["error"] = true;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
}
}
else
{
echo "need to login first.";
}?>
Any ideas what i'm doing wrong?
You can't use DELETE as a form action.
From the specs, we have:
The method and formmethod content attributes are enumerated attributes
with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET method.
The keyword post, mapping to the state POST, indicating the HTTP POST method.
The invalid value default for these attributes is the GET state.
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.
I have a url which has some get variables in it like:
domain.com/recover?email=my#email.com&token=abc123
inside the recover controller i load a form with POST method
so when i submit the form i load again the recover controller but my GET variables disappear and return to
domain.com/recover
so how can i make sure the GET variables retain in the URL after submitting the form?
HTML:
<?php echo form_open('recover'); ?>
<label for="password1" class="fl" style="width:160px;">Your new Password</label>
<input type="text" value="" id="password1" name="password1" style="width:308px;margin-top:0;margin-left:10px;" />
<label for="password2" class="fl" style="width:160px;">Retype your new Password</label>
<input type="text" value="" id="password2" name="password2" style="width:308px;margin-top:0;margin-left:10px;" />
<input type="submit" value="Recover password" class="button_ui" name="submit" />
<?php echo form_close(); ?>
Controller:
$data = array(
'errors' => '',
'show_password_form' => false
);
$get_email = $this->input->get("email") ? trim($this->input->get("email")) : "";
$get_token = $this->input->get("token") ? trim($this->input->get("token")) : "";
if ($get_email != "" && $get_token != ""){
$this->load->model("recover_model");
$data["show_password_form"] = true;
//check new passwords and update
$submit = $this->input->post("submit_change") ? trim($this->input->post("submit_change")) : "";
if ($submit){
$password1 = $this->input->post("password1") ? trim($this->input->post("password1")) : "";
$password2 = $this->input->post("password2") ? trim($this->input->post("password2")) : "";
//if password1 is valid
if ($this->recover_model->valid_password($password1)){
//if password2 is valid
if ($this->recover_model->valid_password($password2)){
//if both are equal
if ($password1 == $password2){
//update password
}else{
$data["errors"] = 'Your passwords do not match.';
}
}else{
$data["errors"] = 'Your password must be at least 6 characters.';
}
}else{
$data["errors"] = 'Your password must be at least 6 characters.';
}
}
}
$this->load->view("account/recover/recover", $data);
Change this line: <?php echo form_open("recover"); ?>
To
<?php echo form_open('recover', $_GET); ?>
it will create all get values as hidden input. When you submit form, they will send with method that you defined for form.
Or you can just write manually:
<?php echo '<form method="post" accept-charset="utf-8" action="'.base_url().'recover?email='.$_GET['email].'&abc='.$_GET['token'].'" />'; ?>
Manually render the form tag in php or the html and add some javascript
<script type="text/javascript">
document.write("<form method=\"POST\" action=\"");
document.write(window.location.href);
document.write("\">");
</script>
Much better js is available for writing this...
Let's say we have this form:
<form action="submit.php" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="Submit" value="Login" />
</form>
How do I validate this form using submit.php, and how do I present an error message if it doesn't pass validation? With Javascript validation I would just change the innerHTML of some element to the error message, but this is not possible with PHP. As you can see I'm a total newbie, so please help me out.
In ugly form:
<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$pw = $_POST['password'];
if (empty($username)) {
$errors[] = "Please enter your username";
}
if (empty($pw)) {
$errors[] = "Please provide your password";
}
if (!canLogin($username, $pw)) {
$errors[] = "Invalid login. Try again";
}
if (count($errors) == 0) {
... login is ok, go do something else
}
}
# Display error conditions, if there are any
if (count($errors) > 0) {
echo "<p>The following errors must be corrected:</p><ul><li>";
echo implode("</li><li>", $errors);
echo "</ul>";
}
?>
<form ...>
<input .... value="<?php echo htmlspecialchars($username) ?>" />
<input ...>
</form>
You could always have the form's action submit to itself (same PHP script) and perform your validation there and if it passes continue to another url. And then in your form write some conditionals to insert a CSS class to highlight the field thats in error or show a message.