How to show error message on previous page? - php

I want to show an error on the same as page as my form. My form is going to another page and then processing and returning the result. How can I show the error on the previous page?
if($_POST['btnManage']=="Signup"){
$objCustomer->Email=$_POST['txtEmail'];
$objCustomer->Password=$_POST['txtPassword'];
$Status=$objCustomer->Signup();
if($Status>0)
{
session_start();
$_SESSION['Email']=$objCustomer->Email;
header("Location:../index.php");
} else
{
echo "error";
}
}

Going with what you have using $_SESSION, you can set eorr in the session.
else
{
$_SESSION["eorr"] = "message_here";
header("Location:../{form_page_here}");
}
Then on the page that has your form, do a check if $_SESSION["eorr"] is set an display the message. You would also need to unset($_SESSION["eorr"]; after it is displayed so it is removed if you do not need to use it again.

Three step to handle the error
step1: define your error code and error message
define('SYSTEM_ERROR',1000);
define('SYSTEM_ERROR_MESSAGE','your error message');
step2: put the current error code to the reference url as a parameter
http://localhost?error=1000
step3: redirect to the reference page ,handle the error code and show to the page
$error = $_GET['error'];
if($error ==SYSTEM_ERROR){
$errorMessage = SYSTEM_ERROR_MESSAGE;
}
//show the $errorMessage

Related

Call function from another page in php

I have a form that user can update their details on page-1.php.
After user submit the form, it will got to page-2.php for validation and update database if user input is true.
May i know how to call a function from page-2.php and display the error message on page-1.php. Below are the function on page-2.php that I use to display the error message:
$_SESSION['err_msg'] = array();
function addError($msg) {
$_SESSION['err_msg'][] = $msg;
}
function printErrors() {
foreach ($_SESSION['err_msg'] as $err){
echo "<ul><li><span style='color: red;'>".$err."</span></li></ul>";
}
unset($_SESSION['err_msg']);
}
//other codes for the validation and update
if i use printErrors();on page-2.php, it will display the error message
You need to include page-2.php in page-1.php. Read this about that.
The best way is to put all your functions in one seperate file, like functions.php and include them on every page with an include.
I think no you don't need function on page-2.php. You can simply check session variable on page-1.php. If $_SESSION['err_msg'] exists and count is greater than 0. Then you can print all errors to page-1.php>
Please check below code.
if(isset($_SESSION['err_msg']) && count($_SESSION['err_msg'])>0 ){
foreach ($_SESSION['err_msg'] as $err){
echo "<ul><li><span style='color: red;'>".$err."</span></li> </ul>";
}
unset($_SESSION['err_msg']);
}
Hope this helps you.
Include the page-2.php in your page-1.php

PHP How to pass error marker after refreshing unsuccessful login

I have a login page and I want to achieve this effect:
If user fails to login, display error message. After user presses refresh button, the error message should not be visible anymore.
I dont want to pass $_GET variable, for example index?page=login$failure. I want to do this in invisible in url way.
<?php
if(isset($_POST['submit_form_register'])) {
...
if($login === false) {
$user->go_to('index.php?page=login'); //Redirects back, cleaning the $_POST data.
}
..
}
?>
Now how do I say for my form, that something before redirect went bad without addint it with $_GET?
Update. So using sessions, can I do like this?
<?php
if(isset($_POST['submit_form_register'])) {
...
if($login === false) {
$_SESSION['is_form_error'] = true;
$user->go_to('index.php?page=login'); //Redirects back, cleaning the $_POST data.
}
..
}
?>
And for HTML output:
<?php if(isset($_SESSION['is_form_error']) and ($_SESSION['is_form_error'] === true)) { ?>
<div>Your email or credential is invalid.</div>
<?php } unset($_SESSION['is_form_error']); ?>
But this one doesnt work for me. I bet its because something wrong with unset. Any tips?
SOLVED: Didn't have exit; after header(); in $user->go_to($url);
You could use Session for show and hide errors
When user enter wrong user/pass you set error session and use it in view and then delete session(after showed)
`//Set Session
if (!$success) {
$_SESSION['login_error'] = 1;
}
//show
if (isset($_SESSION['login_error'])) {
echo "Invalid Username/Password";
unset($_SESSION['login_error']);
}`
Don't forget to start code with session_start();

My php cookie session code displays a blank white page no matter what?

So on one page my users check a box and type agree in an input field to proceed to the next page, I am trying to use session cookies to stop people bypassing this by typing the URL however when you proceed to the next page it just displays blank? i have tried tests such as using Echo to display text at the beginning of the script and have enabled error reporting but the page still just displays white? any ideas why?
Check Box and Input Page php:
<?php
if(isset($_POST["terms"])&&isset($_POST["agree"])) {
$agree = $_POST["agree"];
$validated = false;
if($agree=="agree") $validated = true;
if($validated) {
setcookie("agree",($agree));
header("Location: nextpgae");
} else {
header("Location: homepage");
}
}
?>
Page it leads to that is displaying blank's php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$validated = false;
if(isset($_COOKIE["agree"])){
$agree = $_COOKIE["agree"];
if(&$agree==("agree")) $validated = true;
}
if($validated) {
} else {
header("Location: homepage");
?>
A blank page is usually symptomatic of a server error. Frequently, it indicates a syntax error in your PHP code. Your server error log will tell you exactly what is going on, but in this case you have missed a closing } after this line
header("Location: homepage");
You should implement tokens for this kind of procedure. This may help you: http://forum.codecall.net/topic/58268-form-tokens-with-php/

Login Verification , $_GET['id'] in php not working

THIS is the PHP code m using for checking the values
if($uname==$row['username']) {
if($uname=='' || $pass=='') {
header("Location:login.html?id=Some fields are empty");
} else if($uname==$row['username'] && $pass==$row['password']) {
header("Location:1.html?id=$uname");
} else {
// **HERE I AM REDIRECTING TO THE LOGIN PAGE AND SENDING ERROR MESSAGE AS ID**
header("Location:login.html?id=Incorrect Password");
}
}
In the HTML part I included this to show the error message
<?php
if(isset($_GET['id']))
{
echo $_GET['id'];
}
?>
However NOTHING is getting printed
As mentioned in the comments, make sure that the server is set to parse .html file as PHP. See Server not parsing .html as PHP
The other option is to change your login.html to be login.php and go from there.
you can use php filters to check correctly if the values are set or not like the following :
filter_has_var(INPUT_GET , 'id');
this function returns true or false

Using PHP to request errors information and post if errors has anything

I have an HTML form that takes inputted data and sends it via the mail() function. I also have some validation techniques that validate the inputs, and I created an array variable $errors to log all of the errors; for example,
if the name was left empty, $errors[]="Name empty";
If the email was left empty, $errors[]="email empty";
and so on..
I was able to report the errors using the following technique:
print '<div id="formfeedback"><h3>Error!</h3><p>The following error(s) has occurred:<br />';
foreach ($errors as $msg) { //prints each error
print " - $msg<br />\n";
} // end of foreach
However, what I want is the following. I want the page to be redirected back to the original form that was used to input the information (I know the exact link location, so i can use a header() or even a <meta=http-equiv=refresh> to bring me back to the form page.
Also, on the form, I want to be able to post the errors above the form in some div (call it div=errors)
Would I be able to do the following?
<div id="errors">
<?php
print 'The following error(s) has occurred:<br />';
foreach ($_REQUEST[$errors] as $msg) { //prints each error
print " - $msg<br />\n";
} // end of foreach
?>
</div>
Thanks a lot!
Amit
I agree with #Fosco. I want to explain a little bit more-
There may be two cases-
1. You are doing raw php
2. You are coding on any php framework like CI or your own.
and this will help to identify error field and change style to make better user response. Also last input data remain as it was.
You are doing raw php
In this case you can receive the input data in same file/page.
I will do a common example later.
You are coding on any php framework like CI or your own.
In this case you load a view file to show the form page and you can pass data to view page/file when you load it.
For both of above case you can do some coding like-
/*
your input validation and verification goes here. where $error is generated too
In addition add some error status in above section,
you can do it in your $error array too. Also you store received data into $data here. index of $data should be similar as (corresponding) HTML input name.
You can do it like below
*/
$error_stat = array();
//if the input field name is "email" and email input data raises any error then
$error_stat['email'] = true;
// same for name
$error_stat['name'] = true;
// and so on
// now decide whether you will back to the form page or send the email and do other tasks
if(count($error_stat)<= 0){
// send email
// do aditional tasks
}
else{
// load the form again if its aframework or the form is in seperate file
// off course send $error,$data and $error_stat to the form page/file
}
// now here is a code segment of form page
<?php if(isset($error) && count($error)>0):?>
<div id="error-msg">
<?php
//display errors here
?>
</div>
<?php endif;?>
<form .... >
<input type="text" name="email" class="<?php echo (isset($error_stat['email'])?'error':'else'); ?>" value="<?php echo $data['email'];?>" />\
<!-- and so on ... -->
The simplest way to do this is to:
// Start the session
session_start();
// Store the errors in the session
$_SESSION['errors'] = $errors;
// Redirect to correct page
header('HTTP/1.1 303 See Other');
header('Location: http://original/page');
exit;
Then, on the form page:
// Start the session
session_start();
// extract the errors
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : array();
// Display the form with errors
foreach ($errors as $msg) ... ;
Typically I would have the same page process the input and the submission. If the data was valid, the mail would be sent and the page would notify them of that (or redirect them elsewhere)... if the data was not valid, then the form would appear again and the errors could be displayed, without any fancy redirection.
make sure your session is started at the top of your application
include this basic class
class FormErrors
{
var $handler;
function __construct($fname)
{
$this->handler &= isset($_SESSION[$fname]) $_SESSION[$fname] : ($_SESSION[$fname] = array());
}
public function add($name, $value)
{
$this->handler[$name] = $value;
}
public function remove($name)
{
unset($this->handler[$name]);
}
public function getErrors()
{
return $this->handler;
}
}
so when your processing the errors you can go
if(isset($_POST))
{
$FormErrors = new FormErrors("registration");
if(strlen($_POST['username']) == 0)
{
$FormErrors->add('Username','Please enter a valid username');
}
//And for the rest of your checks
}
then within side your html do
foreach($FormErrors ->getErrors() as $name => $error)
{
echo sprintf("<p title=\"%s\">%s</p>",$name,$error);
}
Should work, and if you want to remove all known errors do
$FormErrors = new FormErrors("registration");
unset($FormErrors->handler,$FormErrors);

Categories