I'm using codeigniter 3, and flashdata to show an error message to the user when inserting an invalid username or password.
The problem is that the message is always showing even when the page was just opened and no password or username was inserted.
EDIT:
The comparison and the authentication are right but when i open the page it still appear even when no action was taken.
this is the form
<?php echo $this->session->flashdata('msg');?>
and this is the controller
public function authentication(){
//post user unput
$empNum=$this->input->post('employeeNum');
$pwd=$this->input->post('password');
$user=$this->empNumAuth($empNum, $pwd);
if($user) {
if($user['PrivilegeLevel']==='1'){
$this->session->set_userdata($user);
redirect('AdminDashboard/view');
}
else if($user['PrivilegeLevel']=='2') {
$this->session->set_userdata($user);
redirect('UserDashboard/view');
}
}
else {
$this->session->set_flashdata('msg','الرقم الوظيفي او رمز الدخول خاطئ');
redirect('Login/LoginPage');
}
From your code, the flashdata is set whenever the authentication fails( $this->empNumAuth() returns false). So if the path /authentication gets called, and no password or username is entered, it passes blank values to the empNumAuth() function, which will definitely return a false value(since blank values were passed, so the authentication will fail). Otherwise, if you feel the flashdata should not be shown, and you are sure valid credentials were submitted, then the problem lies within the empNumAuth() function, start checking from there.
BONUS:
If you are echoing the flashdata message within an error/success div, it will always display, with no text on it. That is, suppose you have an error div formatted with a red background, when you echo the flashdata directly as you did, the error div will be displayed but with blank text. The best way is to check if the flashdata is set before echoing it. See the example below. (I have used default Bootstrap error alert div)
<?php if($this->session->flashdata('msg'){?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('msg');?>
</div>
<?php } ?>
The above code checks if the flashdata is set which will prevent the flashdata div from being displayed always.
Use the above code in view file...
<?php
if($this->session->flashdata('msg')
{
?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('msg');?>
</div>
<?php
}
?>
Related
So, in my corePHP Project I have sign-up.php page with form:
<form method="POST" action="./Controllers/RegistrationController.php">
Now, in this RegistrationController.php I have
$errors=Validator::validateUser($data);
if(count($errors)==0)
{
//here I will add code to insert user to database later
}
else{
// What code to write here?
}
Basically, if array of $errors is empty, data is valid, and user will be inserted into db, otherwise errors will be displayed on sign-up.php page.
My question is how to return these $errors to sign-up.php and show them in my starting form?
You can redirect user to your sign-up.php with sending HTTP-header. Just use header() for this.
You can set your errors as query params, like http://example.com/sign-up.php?error[field]=name&error[message]=empty!
And for generate beautiful params, try to use http_build_query()
In your case:
$errors=Validator::validateUser($data);
if(count($errors)==0)
{
// some success things
}
else{
// I just put all array as params for example
header('Location: http://www.example.com/?' . http_build_query($errors));
exit;
}
In codeigniter we can define the url that should be displayed in the browser. I have a login page which goes well when the credentials are given right. I need to show an error message in the same page itself if the credentials are wrong. For that i have did the followings.
<div style="<?php echo ($status==='err')?'display:block':''?>" class="form-login-error">
<h3>Invalid login</h3>
<p>Please enter correct email and password!</p>
</div>
and
$data['status'] = (isset($_GET['status']))?$_GET['status']:true;
in controllers's index function
if($userdata['status'] == 'success')
{
if(!empty($userdata['userdet']))
{
$this->session->set_userdata($userdata['userdet']);
redirect('dashboard');
}
}else{
redirect('login?status=err');
}
The code works well. but my doubt is can i change the url pattern? It is now showing loclhost/myproject/login?status=err.Can i change this to localhost/myproject/loginerror? I tried to define in routes, but it is showing page not found error. Thanks in advance.
You are making a simple thing much complex by using URL's param's here.
I would suggest using CI session Flashdata. The benefit of using Flashdata is that the session variable is maintained only for the next page and then the session variable is cleared automatically so it is very useful in cases where we need to display some messages to users.
Change your code to something like this :
<div style="<?php echo ($this->session->flashdata('error') )?'display:block':''?>" class="form-login-error">
<h3>Invalid login</h3>
<p>Please enter correct email and password!</p>
</div>
and in your controller :
if($userdata['status'] == 'success')
{
if(!empty($userdata['userdet']))
{
$this->session->set_userdata($userdata['userdet']);
redirect('dashboard');
}
}else{
$this->session->set_flashdata('error', 1);
redirect('login');
}
use the codeigniter application/config/routes.php
$route['myproject/login/(:any)']="myproject/login/$1";
youcan hold the value of parameter in action of controller.
Basically I'v got a HTML Form that links to a php file in a different location for it's action, Currently I'm using the form to update the users profiles and then send them back to the editprofile.php. Basically at the top of editprofile.php if they've submitted the query I want to display the result of either "Profile Updated" or "Failed to Update", issue is I can't workout how to display query results when the query is in a different file.
I tried to do this;
<?php
if(!$query)
{
echo '<div class="editfail">Profile failed to update!</div>';
}
else
{
echo '<div class="editsuccess">Profile successfully updated!</div>';
}
?>
Except the issue with this is that the query hasn't been run on this page, it was run from another page and then redirected back to the editprofile page using a header, so how can I display the same results as above when the query is being executed from another location?
You can send parameter when you are redirecting back the file.
example
if(mysql_query($update_query))
{
header('location:editprofile.php?msg="success to save"');
}
else
{
header('location:editprofile.php?msg="failed to save"');
}
Or even you can send flag also
if(mysql_query($update_query))
{
header('location:editprofile.php?flag=0');
}else
{
header('location:editprofile.php?flag=1');
}
And check the value of flag in your editprofile.php file to display proper message.
You shouldn't mess around with the headers fxn unless you need to - depending on output_buffer settings etc they can be a pain:
You can do what you want - all in 1 single page:
So something like this -As a matter of common convention, and to a degree security, you should post the form to itself - you can integrate whatever else from the other page into the pass/fail profile logic block:
<?php
$query = htmlentities($_POST['profiletext']); #sanitize avec tu code du jour
if(!$query || $query != 'someacceptablevalue))
{
#If it's not posted, or its not a good value, tell them it failed
# and redisplay the form to try again
$query_msg = '<div class="editfail">Profile failed to update!</div>';
$profile_form = "<div_class='profile_rest_of_page stuff'>
<form action='#' method='post'>
<input type='text' id='profiletext' name='profiletext/>
</form>
</div>";
}
else
{
# They did it - Success, and link to next step
$query_msg = '<div class="editsuccess">Profile successfully updated!</div>';
$profile_form = 'No form needed - you did it';
}
#One block below handles all in 1 page with above logic:
echo "<body>
<div class='profile_message_container'>
$query_msg
</div>
<div_class='profile_rest_of_page stuff'>
$profile_redo<br/> You did it <a href='next'>next</a>
</div>
</body>
";
?>
You can do this in two ways:
Send the query results in the link like a GET which could be tampered with
Process the form in the same page that has your form as follows
if(isset($_POST['some_name'])) {
// Process form
} else {
// Display form
}
My developer built our registration page to display a div when logins failed based on a string in the URL.
When logins fail this is added to the URL /login?msg=invalid
The PHP in my login.phtml which displays the error messages based on the msg= parameter is
<?php
$msg = "";
$msg = $_GET['msg'];
if($msg==""){ $showMsg = ""; }
elseif($msg=="invalid"){ $showMsg = ' <div class="alert alert-error">
<a class="close" data-dismiss="alert">×</a>
<strong>Error!</strong> Login or password is incorrect!
</div>'; }
elseif($msg=="disabled"){ $showMsg = "Your account has been disabled."; }
elseif($msg==2){ $showMsg = "Your account is not activated. Please check your email."; }
?>
In the controller the redirect to that URL is
else //email id does not exist in our database
{
//redirecting back with invalid email(invalid) msg=invalid.
$this->_redirect($url."?msg=invalid");
}
I know there are a few other validation types for disabled accounts etc. I'm in the process of redesigning the entire interface and would like to get rid of this kind of validation so that the div tags display when logins fail but not show the URL strings.
If it matters the new div I want to display is
<div class="alert alert-error alert-login">
Email or password incorrect
</div>
I'd like to replace the php my self in my login.phtml and controller but not a good programmer. What can I replace $this->_redirect($url."?msg=invalid"); with so that no strings are added to the URL and display the appropriate div tags?
Thanks
Passing a msg through a GET parameter is a bit weird to me.
See this thread discussing other ways to send a message to the page, using sessions, cookies or database, here.
I'm not familiar with the zend framework, but there has to be a way to set a "flash" message through the session.
change this in loginAction of your contorller
$this->_redirect($url."?msg=invalid");
to
$this->view->message = $msg;
then add to your code to login.phtml
<?php if ($this->message) :?>
<div class="alert alert-error alert-login">
Email or password incorrect
</div>
<? endif; ?>
... your form code there
I have a list of comments for a given article and I have a form underneath the comments for a user to add their own comments.
I'm using php to do some form validation.
This is the process:
User fills out form (or not) and hits submit button. page refreshes.
PHP validates user input and either submits comments if no errors or
generates a list of errors.
If errors exist display the errors.
The problem is that I want the errors to display underneath the comments before the form which it does but when th epage refreshes, the top of the page is displayed and i need it to go straight to the errors and form (much like a page anchor)
Is this possible?
This is called after the submit button is clicked
if(empty($errors)){
$result = post_comment('event',$event_id, $sendername, $senderemail, $userurl, $comment);
if ($result == 'Correct') {
//header('Location: /'.$_SERVER['REQUEST_URI']);
header('Location: '.$_SERVER['REQUEST_URI']);
}
else {
$send_error = $result;
and this is near the comments and form where i want to page to go to if errors exist
// If there was an error sending the email, display the error message
if (isset($send_error)) {
echo "<a name=\"commentsform\"></a>";
echo "There was an error: ".$send_error;
}
/**
* If there are errors and the number of errors is greater than zero,
* display a warning message to the user with a list of errors
*/
if ( isset($errors) && count($errors) > 0 ) {
echo ( "<h2 class='errorhead'>There has been an error:</h2><p><span class='bold'>You forgot to enter the following field(s)</span></p>" );
echo ( "<ul id='validation'>\n" );
foreach ( $errors as $error ) {
echo ( "<li>".$error."</li>\n" );
}
echo ( "</ul>\n" );
}
}
}
Give the form an ID which can be jumped to via the URL:
<div id="submitComment">
<!-- Comment form here -->
</div>
And then redirect the user back to the same URL with the appropriate hash tag:
header('Location: http://www.example.com#submitComment');
Find your form tag, it will look something like this
<form action='yourpage.php'>
Put a hash tag after the URL along with the anchor it will go to upon submission-
<form action='yourpage.php#commentsform'>
Using page anchors you can jump the user to any part of the page by changing the hash in the url.
Make the form send the user to to anchor like so:
<form action='yourpage.php#comments'>
And make an anchor where you want your user to end up:
<a name="comments"></a>