Printing a PHP error inline instead of erasing the entire page - php

How can I make PHP print an error inline instead of changing the entire page?
I'd like it to target #errors and fill that instead of changing everything.
The code I'm currently using is die ("Incorrect username or password.");
I'm very new to PHP so sorry if this is a pretty easy thing to do.

Put the error in a variable where you do your logic and print its contents in #errors. For example:
if (username_is_incorrect()) $error = 'Incorrect username or password.';
And in the HTML
<?php if (isset($error)):?><div id="errors"><?=$error?></div><?php endif;?>

There are 2 ways of doing it.
A real inline method is not entirely PHP-based, as it cannot be used without JavaScript and AJAX calls.
Note the irritating disadvantage of this method: you will need to re-check every field again upon receiving form data finally.
Another one will reload your page but it will be the same page with all the form fields, entered data and also freshly generated error messages. This is called POST/Redirect/GET pattern
here is a short example
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>

Related

How to redirect to another page in php?

Here is the code for registration. Values are inserted properly but page is not redirected to another page:
if(isset($_POST['submit'])){
$company_name = $_POST['company_name'];//check whether form is submitted or not
$email = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);//email validation
$password = sha1($_POST['password']);
$phone = $_POST['phone'];
$city = $_POST['city'];
$profession = $_POST['profession'];
check validation of email
if(!filter_var($email,FILTER_SANITIZE_EMAIL)){
echo 'invalid email';
}
else
{
$result = mysql_query("SELECT * FROM registerpro WHERE email = '$email'");selecting email from database
$data = mysql_num_rows($result);//check if there is result
if($data==0){
$qry = mysql_query("INSERT INTO registerpro (company_name,email,password,phone,city,profession) VALUES ('$company_name','$email','$password','$phone','$city','$profession')");
here i is the problem as page is not redirecting to another page so please tell me how to fix it
if($qry){
header("Location : company_info.php");//redirect to company_info
}
else`enter code here`
{
echo 'error';
}
}else{
echo 'invalid email';
}
}
}
?>
After registration page is not redirecting to company_info.
Remove extra space after Location
So, change
header("Location : company_info.php");//redirect to company_info
To:
header("Location: company_info.php");//redirect to company_info
// ^ here
I finally figured this out after struggling a bit. If you perform a web search on the PHP header() function you will find that it must be used at the very top of the file before any output is sent.
My first reaction was "well that doesn't help", but it does because when the submit button is clicked from the HTML input tag then the header() function will get run at the top.
To demonstrate this you can put a section of PHP code at the very top with the following line...
print_r($_POST);
When you then press the "Submit" button on your web page you will see the $_POST value change.
In my case I wanted a user to accept the Terms & Agreement before being redirected to another URL.
At the top of the file before the HTML tag I put the following code:
<?php
$chkboxwarn = 0;
/* Continue button was clicked */
if(!empty($_POST['continue']) && $_POST['continue']=='Continue'){
/* Agree button was checked */
if(!empty($_POST['agree']) && $_POST['agree']=='yes'){
header('Location: http://www.myurlhere.com');
}
/* Agree button wasn't checked */
else{
$chkboxwarn = 1;
}
}
?>
In the HTML body I put the following:
<form method="post">
<input type="checkbox" name="agree" value="yes" /> I understand and agree to the Terms above.<br/><br/>
<input type="submit" name="continue" value="Continue"/>
</form>
<?php
If($chkboxwarn == 1){
echo '<br/><span style="color:red;">To continue you must accept the terms by selecting the box then the button.</span>';
}
?>

PHP submit form on same page with echo shown below form

I'm aware that this question has been asked a huge number of times but the answers seem really specific to the script posted and with my current knowledge I can't make the transition from the corrected script to implementing it into my own.
This all works fine - it submits on the same page and provides feedback of any errors, but I want any errors to be echoed beneath the form making it more convenient for the user to just change what they entered incorrectly and re-submit.
From what I can gather from the questions I read before posting this - it may only be possible using jQuery/Ajax?
My script:
<?php
if(isset($_POST['submit'])){
require "connection.php";
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$repeat_password = $_POST["repeat_password"];
$username_query = mysql_query("SELECT id FROM users WHERE username = '$username'");
$email_query = mysql_query("SELECT id FROM users WHERE email = '$email'");
if($username == "" || $password == "" || $repeat_password == "" || $email == ""){
die("All boxes must be filled out!");
}// ^ Checking if all boxes have been filled out
else {
if (!ctype_alnum($username)){
die("Username can only contain letters and numbers");
}// ^ Checking if username is alphanumeric
else {
if (strlen($username) < 6 || strlen($username) > 15){
die("Username must be between 6-15 characters.");
}// ^ Checking if username is between 6-15 characters
else {
if (mysql_num_rows($username_query) != 0){
die("Username is taken, please choose another.");
}// ^ Checking if username exists in database
else {
if (!preg_match("/[0-9]/",$password)){
echo "password doesnt contain a number";
}
else {
if ($password != $repeat_password){
die("Passwords do not match");
}// ^ Checking if password and repeat_password match
else {
if (strlen($password) < 6){
die("Password must be atleast 6 characters long.");
}// ^ Checking if password is longer than 6 characters
else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
die("E-mail address is not vaild.");
}// ^ Checking if e-mail address is valid
else {
if (mysql_num_rows($email_query) != 0){
die("This e-mail address has already been used to create a different account.");
}// ^ Checking if e-mail address has already been used
else {
mysql_query("INSERT INTO users (username, password, email, signup_date) VALUES ('$username', '$password', '$email', CURDATE())") or die(mysql_error());
echo "Account succesfully created, welcome ".$username."!";
}
}
}
}
}
}
}
}
}
exit;
}
//
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>
Username:
</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type="password" name="password">
</td>
</tr>
<tr>
<td>
Repeat password:
</td>
<td>
<input type="password" name="repeat_password">
</td>
</tr>
<tr>
<td>
E-mail:
</td>
<td>
<input type="email" name="email">
</td>
</tr>
<tr>
<td colspan="2">
<center><input type="submit" name="submit"></center>
</td>
</tr>
</table>
</form>
Answer: Yes, you have to use jQuery there.
You can validate form just after user entered 1st letter. You can validate on key up/down or on submit. I suggest to use jQuery Validation Plugin.
To sumbit form use ajax requests. It is rly simple. You can read about it here. There are some examples at the end page I had given.
Note, that if you will use jQuery Validation Plugin you can send ajax request on valid action. Using this, ajax request with serialized form will be sent on form submit + on form valid. If form has some invalid fields, errors will be shown, if there are no errors, ajax-request will be send.
Advice:
Your arhitecture not very good. Why? If people will write bad name and make 10 more other errors, only 1 error:
Username can only contain letters and numbers
will be shown. Why? Because of you arhitecture. After that he will correct 2nd erorr. 3rd error etc.
I suggest you do to handle errors this way:
$errors = array();
$errorsFlag = false;
if(check_username1()) {
$errors[] = 'Tell about this error';
$errorsFlag = true;
}
if(check_username2()) {
$errors[] = 'Tell about this error';
$errorsFlag = true;
}
if(check_mail()) {
$errors[] = 'Tell about this error';
$errorsFlag = true;
}
And how to output it? Use this:
if($errorsFlag == true) {
foreach($errors as $error) {
echo $error . " <br /> ";;
}
}
yes, you'll need javascript. but not necessarily jQuery or ajax.
but php without the use of ajax always needs you to reload the page cause otherwise the php-code will not be executed.
search for some kind of javascript/jQuery validation scripts if you don't want the page to be reloaded. otherwise (if you don't care about page-reloading), you can put out your error message at the end of the form with php as well.
I always set my errors as a session. This allows you to set multiple errors at once, and print them wherever you want.
The following if statements are just examples of where you would set the errors...
session_start(); //you will need this
if ( username_exists($un) ) {
handleError("Username already exists!");
}
...
if ( !passwordIsStrong($pw) ) {
handleError("Password is not strong enough!");
}
Here's the functions that actually set/print the errors.
function handleError( $err ) {
//get any existing errors
$existing = isset($_SESSION['form-errors']) ? $_SESSION['form-errors'] : '';
//append the new error to the existing ones. Over-write the session with new data.
$_SESSION['form-errors'] = "$existing<li>$err</li>";
}
function getErrors() {
if( isset($_SESSION['form-errors']) )
echo $_SESSION['form-errors'];
}
getErrors(); can be called anywhere in your html. It will print something like this...
<li>Username already exists!</li>
<li>Password is not strong enough!</li>
It's kind of like a log. But it's worked for me on all of my projects!

Input does not pass validation test for strlen

I am making a login system and I have a form with some validation.
However my form seems to be failing to pass the validation even though the data input should pass easily.
See:
http://marmiteontoast.co.uk/fyp/login-register/index.php
When you input a username, it should be over 3 characters. But even if you enter one really long you get the error message: The username is less than 3 characters.
EDIT: There was an issue in my copying from formatting that caused a missing }. I've corrected this. It wasn't the issue.
This is the if statement for the username pass. So it seems like it is not getting past the first test:
if (isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
$_SESSION['status']['register']['username'] = $username;
if(strlen($username) > 3){
if(strlen($username) < 31){
if(user_exists($username) === true){
$_SESSION['status']['register']['error'][] = 'That username is already taken. Sorry, please try again with a different username.';
}else{
// passed
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 3 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is not entered.';
}
And this is the HTML for the username:
<form method="post" action="register.php">
<div class="username">
<label class="control-label" for="inputUser">Username</label>
<input type="text" id="inputUser" name="username" placeholder="Username" value="<?php echo $usern_value; ?>" />
</div>
You can see the site here: http://marmiteontoast.co.uk/fyp/login-register/index.php
Session
The index page does use sessions.
It starts with this:
<?php
session_start();
?>
And kills the session at the end of the file:
<?php
unset($_SESSION['status']);
?>
But in the file it starts new sessions which store the inputs. This is so if you make a mistake, it still holds your info so you can adjust it rather than having the fill in the form again. Here is an example of where it grabs the username and saves it, then outputs it.
<?php
if(isset($_SESSION['status']['register']['username'])){
$usern_value = $_SESSION['status']['register']['username'];
} else {
$usern_value = "";
}
?>
value="<?php echo $usern_value; ?>" />
This is the user-exists function:
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
Ah, I can see the problem from your website link. When the error pops up ("The username is less than 3 characters."), try refreshing your browser. I expected to receive a browser warning that says the data would be resubmitted to the server — because you are in a post form — but I did not.
So, what does this mean? It means that immediately after validation failure, you are redirecting back to the same screen, and — unless you are using a session to preserve this information — your $_POST data will be lost. Commonly in the case of validation failure with this sort of form, you must prevent that redirect and render inside the post operation, which keeps the user's input available to you. The redirect should only occur if the form input was successful (i.e. it saves to the data and/or sends an email).
Edit: I should have seen the $_SESSION in the original post. OK, so the strategy is to write things to the session, redirect regardless of validation outcome, and to save error messages to the session. I wonder whether you are not resetting the session errors array when you're posting the form? Immediately after your first if, try adding this:
if (isset($_POST['username'])){
$_SESSION['status']['register']['error'] = array(); // New line
Unless you have something to make the session forget your errors, they will be stored until you delete your browser's cookie.
You have missed a closing brace } on this line:
if(user_exists($username) === true){
} else{// **missed the closing brace before the else**
// passed
}
Why is your logic so complex?
if (strlen($username) < 3) {
// too short
} elseif (strlen($username) > 31) {
// too long
} elseif (true === user_exists($username)) {
// already registered
} else {
// passed
}

Global error message in php

I have a problem with the understanding of variable scopes.
I've got a huge .php file with many $_POST validations (I know that isn't not good practise). Anyways I want a little html-part above all the code which outputs an error message. This message I want to change in every $_POST validation function.
Example:
if($ERR) {
echo '<div class="error-message">'.$ERR.'</div>';
}
Now my functions are following in the same file.
if(isset($_POST['test']) {
$ERR = 'Error!';
}
if(isset($_POST['test2'] {
$ERR = 'Error 2!';
}
But that doesn't work. I think there's a huge missunderstanding and i'm ashamed.
Can you help me?
I didnt catch your question but maybe this is your answer:
<body>
<p id="error_message">
<?php if(isset($ERR)){echo $ERR;} ?>
</p>
</body>
and I suggest you to learn how to work with sessions.
and you should know that $_Post will be empty on each refresh or F5
You can do put the errors in array make them dynamic.
<?php
$error = array();
if (!isset($_POST["test"]) || empty($_POST["test"])) {
$error['test'] = "test Field is required";
} else if (!isset($_POST["test1"]) || empty($_POST["test1"])) {
$error['test1'] = "test Field is required";
}else{
//do something else
}
?>
You can also use switch statement instead of elseif which is neater.

PHP, display message if one or more fields is empty

What I want is to show the error (message), only if the user do a false action. For example, if the field is empty, it will show (Please fill all the fields). I've already done that, but the problem that I have is that it shows also if the user enter to the page for the first time, meaning it does NOT respects the (if condition) that I have written !
The question :
How to show the message only if one of the fields is empty ?
Any ideas on how I can solve it ?
Here is my code :
<?
$conn = mysqli_connect('localhost', 'db', 'db_pass', 'db_name') or die("Error " . mysqli_error($conn));
$email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
$old_password = trim($_POST['old_pass']);
$new_password = trim($_POST['new_pass']);
$email = mysqli_real_escape_string($conn,$email);
$old_password = mysqli_real_escape_string($conn,$old_password);
$new_password = mysqli_real_escape_string($conn,$new_password);
if(empty($email) || empty($old_password) || empty($new_password)){
echo 'Please fill all the fields !<br>';
}
else{
$sql="UPDATE users SET pass='$new_password' WHERE email='$email' AND pass='$old_password'" or die("Error " . mysqli_error($conn));
$result = mysqli_query($conn,$sql);
mysqli_close($conn);
}
if($result){
echo'Password changed successfully !';
}
elseif(!$result) {
echo 'The email/password you provided is false !';
}
?>
Validation of any form happens in the "action" file within a condition i.e. the validation should be subjected to the event of user clicking the submit button. For this to work you should check that
1. Your form has a submit button with a name property set to say submit (can be anything)
eg: <input type="submit" name="submit" id="someid" value="Submit" />
2. The form must have action property pointing to a processor file
eg: <form action = "somefile.php" method = "post">
3. In the somefile.php file the validation code must be within a condition which checks for the event of form been submited
eg://somefile.php
<?php
if(isset($_POST['submit']{
//all the validation code goes here
}else{
//for a single page form and validation
// the code for displaying the form can go here
?>
I suggest you to do this:
First define a variable with plain $_POST[] for eg $name = $_POST['name'];
Then, check if all the vatiables you've define are empty or not.
Lastly, Use escape_string() or whatever you want.
The solution is to check for a variable that you know will always be set if the form is submitted, usually the submit button.
For example, if your form ends like this:
...
<input type="submit" name="change_password" value="Change password" />
</form>
then in the PHP code you could check
if(isset($_POST['change_password'])) {
// The submit button was in the POSTed data, so this is a form submit
} else {
// This is a new page load
}
Alternatively, if you are POSTing the data, you can check which HTTP method was used to call the form:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Form was posted
} else {
// $_SERVER['REQUEST_METHOD'] == 'GET'
}
The pattern I commonly use is:
$showForm = true;
if( is_form_postback() ) {
if( data_is_valid() ) {
redirect_to_thank_you_page();
} else {
show_validation_errors();
$showForm = false;
}
}
if($showForm) {
// Print the form, making sure to set the value of each input to the $_POSTed value when available.
}

Categories