flashdata error not displaying - php

I'm having this strange problem with codeigniters flashdata in my login form. When I submit the form with an error in it (unrecognised email or bad email password combo) it takes two submits for the error message to display. Here's the relevant code:
//If an email address is matched
if($rowcount === 1) {
$row = $query->row();
if (hash('sha1', $row->salt . $_POST['password']) === $row->password) {
//there's a matching user...create a session here and redirect to homepage
} else {
$this->session->set_flashdata('credentials_error', '1');
// echo 'recognise email but not password';
}
} else {
//send message back to view here
$this->session->set_flashdata('email_error','1');
}
print_r($this->session);
$global_data['page_data'] = $this->load->view('login-template','',true);
$this->load->view('global', $global_data);
and the relevant bit from the view:
if($this->session->flashdata('email_error')) {
echo '<p class="error">We dont recognise this email address.</p>';
}
if($this->session->flashdata('credentials_error')) {
echo '<p class="error">We dont recognise these details. Please try again.</p>';
}
So if I submit the form with a bad email address that's unrecognised then I set the email_error flash data. The problem is that in the view I can see that the flashdata is set when I print out all the session data ([flash:new:emaili_error] => 1) but my error message does not show. However when I submit the form again (re-sending the same data) the error message shows.
Any ideas why this might be?

Yes; don't be fooled by the name they use, "sessions" in Codeigniter are cookies (they're not a fancy equivalent of the native php $_SESSION array, and they don't use it. Inf act, global arrays are usually destroyed in CI). As such, they're available only at the subsequent request; when you load the view the cookies has just been set: you need to make another request in order for the browser to catch it up and display it.
Usually flashdata are used, in fact, when you want to persist something between 2 http requests, not in the same request you set them and load a view.
It happens that you send a form, you make your checks, then you set the flashdata with the error and in the same process you load a view. The flashdata is "set" in codeigniter's class, only. When you re-submit the form, the cookie is now available, therefore you're shown the message. Hope it's clearer.

I always redirect instead of loading a view to get my flashdata working correctly. When you load a view, it's not submitting a new http request, but when you redirect, it is.

Related

PHP: display message if redirected from PHP file

I'm probably going about this the complete wrong way, but here's where I am at.
I have a page called adminquery.php and on it is a form. When that form is submitted, it calls a file called adduser.php
This page attempts to add the user sent by POST to a database and sends back one of two messages (added or updated) which should display on the adminquery.php page.
if ($row[0] == 1)
{
//update
$_SESSION['errMsg'] = "user updated";
}
else
{
//add
$_SESSION['errMsg'] = "user added";
}
header("Location: adminquery.php");
die();
adminquery.php displays the message
if(isset($_SESSION['errMsg'])){
echo "<p>".$_SESSION['errMsg']."</p>";
}
So far, so good. However, when I reload adminquery.php or access it from another page, I want it to not display this _SESSION message which is no longer applicable.
So I thought I would check the originating page when loading adminquery.php and, if it's not been accessed from adduser.php I would empty the message
$referringSite = $_SERVER['HTTP_REFERER'];
if (strpos($referringSite, 'adduser') == false) {
//$_SESSION['errMsg'] = $referringSite;
$_SESSION['errMsg'] = "";
}
The commented line is used to check the referring page and it displays adminquery.php as the referring page rather than adduser.php (which has been called but not displayed). It seems like unless the page has been displayed or an element on it clicked to reopen adminquery.php that it's not recognised as the referring page.
Is there some simpler solution I'm not seeing?
Setting an empty string won't clear the session variable. You need to unset it like so:
unset($_SESSION['errMsg']);
Also, you don't need to check the referrer. Since the user script sets that variable, the admin query script can just check if it exists, and if so, remove it after displaying the appropriate message.
You must unset this session variable.
if(isset($_SESSION['errMsg'])){
echo "<p>".$_SESSION['errMsg']."</p>";
unset($_SESSION['errMsg']);
}

How to Validate a form in within the same page and when there are no errors send it to another page for further registration?

Okay. I have yet another easy problem which I can't solve. I am working with PHP and I am working on a form to be validated by PHP. I have validated the form in another page containing the same elements. That's the
<form name = "Order Form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">
but now the problem arises is that, when we have validated the form and there are no more errors, how to send the data for further registration in other pages. Assuming that Javascript is off I have to use this method. Help is very much appreciated.
You can use session to store some data for a short time such as registration process example:
<?php session_start();
if(noerror){
$_SESSION['username']=$username;
//similarly do for more
header("Location:next_page.php");
}
else{
//show error
}
Note: Alternatively You can also use hidden input but I will discourage that as for security purpose you need to re-validate that.
Update:
To check if an error has occurred or not no need to count them simply use an variable called $noerror and initialize it with TRUE and as soon as an error occurs set it to false then simply put it in if($noerror) at last.
If you want to display error message store them in an array like $error_log
example:
if(error_in_username){
$noerror=false;
$error_log['username']="Invalid Username";
}
Please refer to below link.
http://www.w3schools.com/php/php_form_url_email.asp
Hope this will solve your problem.
On your validation 'page' which should be a controller of sorts, if validation is successful, load the step2 page with the previous form data in hidden inputs.
OR
After successful validation of step1, save the data already into database (could be a temp table), and then proceed to step2 with the id of the entry you just saved. On submission of step2, you can merge the step2 data with the data of the entry that was saved in the database, and proceed to step3 if necessary. etc.
If you simply want to get to another page, the basic logic is:
if(validation_success)
{
header("Location: step2.php");
} else {
show_errors();
}

form validation not working Codeigniter

I think I am doing everything all right, but why isnt my validation working. Every time the else statement gets executed, even if I enter the valid data.
public function login ()
{
// Redirect a user if he's already logged in
$dashboard = base_url().'dashboard';
$this->user_model->loggedin() == FALSE || redirect($dashboard);
// Set form
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
// Process form
if ($this->form_validation->run() == TRUE) {
echo "Validation Success";
}else{
$this->session->set_flashdata('validation_errors', validation_errors().'<p>Please enter valid email and password</p>' );
redirect(base_url().'login', 'refresh');
}
EDIT
I am using dreamhost VPS .
unless you are on another codeigniter project on another server, just use
redirect('name_of_controller/name_of_method') there is no need to put the base_url() because it already uses the base url as its condition.
and on your validation message set a message like $this->form_validation->set_message('rule','message')
read more at http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#settingerrors
And you have not showed us the view, show us how you post the error message on your view.
1.) have a var_dump() of your session if the validation errors are really set
2.) have you loaded the session library?
3.) Are you sure you are accessing the proper session variables on the view?

PHP redirect to page with variable in URL

I have a page, q.php, that is a user submitted post defined by its id, (for example, q.php?id=1 would be a certain post that uses the $id variable to pull all the rest of the information from the database).
I am trying to code a comment submission on the same page, and account for the fact that a user might not enter anything into the field. If this happens, I want the page (e.g. q.php?id=1) to load again with an error message.
I can do the error message with an empty variable that is then given a value by the php file that the form activates. However, I am having a problem navigating back to the specific post. I tried to use include('q.php?id=$id) where $id is set to a number, but I understand that this is not its purpose and it does not accept variables
What should I be using instead?
EDIT
answer.php (file that the form activates):
require 'q.php';
$_GET['id'] = $id;
$_SESSION['error'] = "Please fill in all of the fields.";
q.php:
if ($_SESSION['error'] !== 0) {
echo "<p style='color: #AA1111;'>".$_SESSION['error']."</a>";
unset($_SESSION['error']); // this isn't happening...
}
If you really must include the page inline, you can always modify $_GET:
$_GET['id'] = $id;
require 'q.php';
But an error message sounds like it could be accomplished with a session variable or a redirect. A redirect could look something like:
header('Location: q.php?id=' . $id . '&error=The+error');
exit();
Then, you check for $_GET['error'] in q.php. Using a session variable for that would be much the same, except instead of adding error as a querystring parameter, you use $_SESSION['error'] and unset it immediately.
You could use header("Location: q.php?id=$id"); exit;, but you would need some other way to send the error message (example: save it in $_SESSION)
You might be able to set the $_GET array how you want it - in this case, $_GET = Array("id"=>$id); then include("q.php"). This is generally considered haxy, though, and may result in problems if you don't use include_once properly.

Prevent form data re-send in Code Igniter

I'm a pretty new with the Code Igniter (as its my first framework I'm learning).
I got this in my controller:
if ($this->form_validation->run() === FALSE)
{
$this->load->view('account/register', $data);
}
else
{
$data['message'] = $this->lang->line('account_created');
$this->register->insert_account();
$this->load->view('account/register_success', $data);
}
If form is validated successfully , it does just change the view, but it is still possible to hit the refresh button, and re-send the form data - its not a big problem for me since I'm checking if fields are unique, but would be better for me to prevent from re-sending the form data.
Normally in clean PHP I would use header("Location: ..."); but I'm loading a view here, so it won't be possible to access it after redirection - isnt it?
Have you any suggestion for that?
You can redirect to the same page but also use codeigniters flashdata in the session library.
On a form submit set the flashdata with a success message.
Redirect to the same page with the form and display the flashdata success message.
By redirecting the page is reloaded and prevents a refresh.
controller
Do this on form success
$this->session->set_flashdata("success", $strMessage);
redirect("account/register");
view
This will show a success message on the form page
if($this->session->flashdata("success") !== FALSE)
{
echo "<div class=\"formSuccess\">" . $this->session->flashdata("success") . "</div>\n";
}
Ajax the view you need into a div. See what I mean? change the contents of the page but not the page itself.

Categories