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?
Related
I'm pretty new to programming and gotta do a project for school. My task is to wrinte a ticketsystem with login etc. in PHP.
Since my groupmates aren't to helpful at all i decided to just code the loginsystem and create a .php which loads content dynamicly.
For normal links things went smooth so far but the loginsystem + the dynamic system gives me headache already.
Whenever i hit the login button (even when I don't enter any logindata at all) I endup in the frontpage(home.php) with the header tellin me that I'm on the "user.php".
I don't get any errors or anything, there seems to be just soem logical errors which i don't get :-(
can anybody help me with this?
http://pastebin.com/5XMSje07
Add exit() under all of your header() redirects
What's your directory structure looking like?
It seems like you don't have a check for empty fields when the post comes in. There should be something along the lines of the following in your login function when the post is read in:
if($_POST['Login'] == null || $_POST['Password'] == null)
{
return false;
}
else
{
//do the login check with the sql call to match username and pw
}
Redirects should be used more sparingly than you appear to have done
In your login script, you have:
if(!isset($usergroup))
{
login();
} else {
logout($usergroup);
}
This is all very well if you assigned $usergroup from a $SESSION value, which you haven't done. This page will therefore always show the login form.
$usergroup = $_SESSION['user'];
would be a start.
You also have multiple session_start calls, as it says in Highlander, "There can be only one".
Your code to detect whether someone has posted data to your script is inside the functions and probably should be inside the above test. Something like...
if (!isset($usergroup)) {
// have we recieved post data to login, if logged in set usergroup)
// if we have not logged in, show the login form
}
if (isset($usergroup) {
// show the logout form
}
i have a secure login form and at the moment, i have set it to just redirect to a home page link, but i want to add some validation so that IF a user comes from a perticular page then they should be redirected to that page after logging in, but not sure how to do it, my current way is not working, here is what i have tried so far:
print $_SERVER['HTTP_REFERER'];
$previousPage = $_SERVER['HTTP_REFERER'];
if ($errors == "") {
if (do_login($form_email_address,$form_password)) {
// success!
if ($previousPage == "http://hiddensite/path/video/"){
redirect($previousPage);
}else{
redirect("/index.php?page=home&loggedin=1");
}
} else {
$errors = "Could not login. Please check your e-mail address and/or password and try again.";
}
and if your wondering what redirect() is, its just my function:
function redirect($url) {
// this function redirects from one page to another
ob_clean();
header("Location: $url");
exit();
}
Do you want to know if a user comes from another page on your own site? If so, you could add a session var to that previous page and test it on your login page.
On your previous page:
session_start();
$_SESSION['foo'] = "bar";
And on your login page -
if(isset($_SESSION['foo'])) {...}
Not a great way to keep track of referrers, but if you only want to check one page as per your question, this should work.
We seem to be missing some information in answering your question. The code you have provided seems fine but in order for us to pinpoint the issue we would have to see the do_login function as you previously posted in the comments (which is now retracted). Since you are always redirected to the home page that would mean that the do_login function always returns false or anything else but true.
Before you retracted the comment I did noticed you also used the sqlslashes() function a few times. Is this a function that you have created? Be sure to include this in your question.
Note : The question is not as simple as the title suggests. However since I could not think of anything better, i typed what i think is closest to my problem.
I have an html page(lets call it firstpage) which has 2 forms( since form processing is via php, it is basically a php page). The php code for the page is as here . One form is for a registered user to login and one form is for the registration of a new user. Following multiple online tutorials I followed the procedure of submitting the form to the page itself using method="post" action="<?php echo $_SERVER['PHP_SELF']?>" . However since Im doing this for both the forms, i now have following issues:
1.The php file which checks various constraints of a new user during registration is executed as soon as i load firstpage which should ideally be executed only when the user fills up the form and clicks on register. Due to this a bunch of php messges strings are always displayed on loading firstpage
2.I do not know how to redirect to the homepage which is the page that should appear when a new registration is successfully completed and also when a registered user is logged in. Any help will be REALLY helpfull. php script for to check for a registered user is here
For the conditions 1 & 2, Follow this
1.
Replace your if statement from
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (!empty($_POST['action']))):
to
if (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['action']) && (!empty($_POST['action']))):
//Assuming $_POST['action'] is the name of your submit button.
2.
Make use of the header to redirect to certain page
Something like this
if(isset( $_SESSION['userid'] ))
{
$message = 'Users is already logged in';
header("location:profile.php");
exit;
}
As for 1. the usual way to go around this is having boolean variables to keep track of the validity of each field (say, isEmailValid) that are by default set to true until the form was submitted.
$isEmailValid = true;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$isEmailValid = false;
function verifyEmail($email);
}
As for your 2nd question, after all checks are done and you stored the record of the new user into the database you could do just
header('Location: index.php');
exit();
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.
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.