I am using sessions to make a multi-stage form, I want to record the information through each stage using codeIgniter sessions then input the session info all into the database at the end.
What I want to do is go from stage 1 in the form, enter a number into an input box, submit it, grab the input number through post and set that number from the post in the session. Then in stage 2 grab the information from the session and simply echo it, then at least I know it's working.
I had my code working earlier, but after moving it around and clearing the cache in chrome it suddenly stopped working and I can't see anything that's wrong with. Please note I'm working in chrome, but I've also tried this in firefox and ie. I am loading the session library with config/autoload and have my encryption key set in the config. I have tried closing chrome and reopening it. Any help would be most appreciated!
Controller: "scholarshiphistory.php"
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Scholarshiphistory extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('site_model');
}
//stage 1 of multipart form
public function addhist_selectstudent(){
$this->load->helper('form');
$data = $this->site_model->general();
$this->load->view('view_addhist_selectstudent',$data);
$this->load->view('view_footer',$data);
//set session info if user submits
if($this->input->post('studentSearch')){
$this->session->set_userdata('studentNationalId', $this->input->post('studentSearch'));
}
}
//stage 2 of multipart form
public function addhist_scholarshipdetails(){
if (!$this->session->userdata('studentNationalId')) {
//no session
$data["msg"] = "<strong>No session!</strong>";
} else {
//get the userinput from the session
$userinput = $this->session->userdata('studentNationalId');
$data["msg"] = "ID:". $userinput;
}
$this->load->view("view_addhist_scholarshipdetails",$data);
}
View: Stage 1 - "view_addhist_selectstudent.php"
<?php $formAttributes = array('role' => 'form', 'style' => 'width: 600px;'); ?>
<?php echo form_open('scholarshiphistory/addhist_scholarshipdetails', $formAttributes); ?>
<div class="form-group">
<div class="panel panel-default">
<div class="panel-body">
<div class="form-group">
<label for="studentSearch">Student:</label>
<input type="text" name="studentSearch" class="form-control" id="studentSearchInput" placeholder="student num" value="">
<br>
<span id="searchResult" class="help-block" ></span>
<button id="studentSearchBtn" class="btn btn-default">Search</button><!--search button returns info on user input in span above-->
</div>
</div>
</div>
<button id="studentSubmitBtn" type="submit" class="btn btn-default" >Next</button> <!--this is the submit button-->
</div>
</form>
View: Stage 2 - "view_addhist_scholarshipdetails"
<?php echo $msg; ?>
When I run the code I get to the view 'view_addhist_scholarshipdetails' and it shows the first branch of the if statement in the function addhist_scholarshipdetails in the controller, i.e "no session".
I moved the code to set the session from the first method in the controller to the second method (also in the controller) and it works okay now, i.e. the session is getting set with the set_userdata method!
Second method now looks like this:
//stage 2 of multipart form
public function addhist_scholarshipdetails(){
if($this->input->post('studentSearch')){
$this->session->set_userdata('studentNationalId', $this->input->post('studentSearch'));
}
if (!$this->session->userdata('studentNationalId')) {
//no session
$data["msg"] = "<strong>No session!</strong>";
} else {
//get the userinput from the session
$userinput = $this->session->userdata('studentNationalId');
$data["msg"] = "ID:". $userinput;
}
$this->load->view("view_addhist_scholarshipdetails",$data);
}
The method I was trying previously seemed to work okay for this guy: http://runnable.com/UhIVTnEfFJEMAAB5
But I think it was because he wasn't setting his session in the same way I was.
Thank so much to those guys who responded to the question.
Related
$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
$_Get methods do not work because of how the login system is built and unsecured.I need mailuid value to bring them to their own profiles page after login.
Login Form since its's post method I should be able to grab the value on other pages and this one
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
Temporary check for the mailuid value. Supposed to grab the value form the login form a spit it back out, to check to see if it is recognized
<?php
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
?>
First I would clean this up:
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
Instead it can be written more concise:
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
if( $user ){
echo "{$user} is your username";
} else {
echo "no username supplied";
}
I prefer Boolean false over NULL, null just means it doesn't exist. Boolean false lets you know you checked it and it didn't exist. Generally should should access $_POST as few times as you can. This is because you should never trust $_POST.
$_Get methods do not work because of how the login system is built and unsecured.
Post is no more secure than get, it's quite easy to post anything to the page even without visiting the site by using something like PostMan etc. Once you assign it to a local variable you know you have at least normalized the data, even if you haven't sanitized it yet.
Also don't forget to call session_start before trying to access $_SESSION. Because of the vagueness of the question, it could be that the form works fine, just the session data isn't being maintained because you haven't started the session yet.. etc....
Hope it helps.
Personally I would clean up the HTML part that makes the form as well, so instead of this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
I would do something like this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php if (!isset($_SESSION['Id'])){ ?>
<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>
<?php }else{ ?>
<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
<?php } ?>
</section>
</div>
</div>
See how much cleaner that is. Most of this is just readability issues. For example there is no need to check if isset($_SESSION['Id']) in the else if condition, because it's either set or not. This is one less place to maintain the session variable key, and it makes the code less convoluted.
As for the actual problem, as long as you are reaching the above code after submission of the form, it should work. So that leads me to believe that you have something wrong in the action.
You should get a clean page after going to includes/login.inc.php meaning there shouldn't be much in the way of HTML. One thing you can do that is real simple is just add at the top:
die(__LINE__.' of '.__FILE__);
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
//... other code
What this will do is die which kills PHP execution, but outputs the argument you passed in. In this case I'm just putting the line and file that the die is on, that way it's easier to find later. But the point is to see if you are even hitting the correct ending script or the forms action/endpoint.
I only suggest this because you are really vague in what it's current behaviour is
$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
For example, this doesn't tell me if you are even hitting the right page. Now had you said something like "all it does is output no username supplied". Then I would at lest know that. As I said above it could be just an omission of sesion_start() which must be called before attempting to access any $_SESSION stuff. You should call it only once, at the top of each page that uses sessions.
Although it's not a solution, it was too much to post in a comment. I would really like to help you more, but there just isn't enough information to go on.
once again I'm lost. I'm gonna start ahead with the issue, because I am not even sure what I really want.
Example:
I have an article view. The URL is: http://index.php/news/article/3
This actually runs the article($id) function in my news controller and gives it the 3 as an argument. The function then fetches the article information and displays it in the view.
On the article page, the user can also log in. Logging in is triggered on pressing
submit button inside my form form_open('core/login')...button...</form> In the function I log the user in and refresh the current view with some elements changed according to the user being logged. The problem is that the URL is now http://index.php/core/login. Obviously I would like it to be the original URL.
Is there any, possibly simple, solution to achieve this? Thank you all for reading and in advance for your replies.
Difficult without more code but let me give you my theory / take on this:
Default controller:
User is not logged in - show default header, content, footer
User presses login, form is shown
User is authenticated - yes (continue) no (go back to form)
User is redirect('home')'d
Your default controller/home controller checks if auth'd: if authorised then show logged in header, content and logged in footer
or simply pass 'loggedIN' as a $data['loggedIN'] variable to the view - but this breaks the ideology of MVC framework.
More info from you and I can be more specific, or we can talk on IRC.
Adding this code from a controller i'm working on right this minute - I use ion_auth library (you should look it up, it's excellent).
This is my default controller - and as you can see some simple logic loads the different views/states.
public function index(){
if ($this->data['auth_login'] ) {
/*is already signed in so just present the lobby?*/
$data['page_title'] = "HN Lobby";
$data['menuItems'] = nav_anchor_helper_authd();
$data['myUserID'] = $this->ion_auth->get_user_id();
$data['lobby_players'] = $this->lobby_model->get_players();
$this->load->view('template/public/header',$data);
$this->load->view('player_pages/nav_2',$data);
$this->load->view('player_pages/lobby',$data);
$this->load->view('template/scripts/main',$data);/*scraper and other scripts*/
$this->load->view('template/public/footer',$data);
} else {
/*request login*/
$data['page_title'] = "PLAY HN";
$data['menuItems'] = nav_anchor_helper();
$data['auth_rtnurl'] = current_url();
$data['auth_conturl'] = current_url(); /*for now just come back to same page where lobby should load - perhaps in future a semi gooey login? e.g where was user going - this could be the continue url in this var right here << */
$data['message_body'] = $this->session->flashdata('message');
$this->load->view('template/public/header',$data);
$this->load->view('template/public/nav_1',$data);
$this->load->view('public_pages/play',$data);
$this->load->view('template/public/footer',$data);
}
}
Here is how I handle the return URL in my login function:
Login/auth controller: (using ion_auth)
function login()
{
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
$rtnurl = $this->input->post('auth_conturl');
if(!$rtnurl || $rtnurl == ""){
$rtnurl = '/';
}
redirect($rtnurl, 'refresh');
}
This is only an extract/segment of the login function - but as you can see i utilise the function 'redirect' from code igniter to push the user back to the return URL posted with the login form (which was set in the view/previous controller using the current_url() function.
Finally my default view file with login form to show you how i am passing the return url:
<div>
<h4>Login</h4>
<div id="infoMessage" class="errortext"><?php echo $message_body;?></div>
<?php echo form_open('auth/login', array('class' => 'form col')); ?>
<p>
<label for="identity">Email:</label> <input type="text" name="identity" value="" id="identity"> </p>
<p>
<label for="password">Password:</label> <input type="password" name="password" value="" id="password"> </p>
<p>
<label for="remember">Remember Me:</label> <input type="checkbox" name="remember" value="1" id="remember"> </p>
<p><input type="submit" name="submit" value="Login ยป"></p>
<p>
Forgot password ?
</p>
<input type="hidden" name="auth_rtnurl" value="<?php echo $auth_rtnurl; ?>"/>
<input type="hidden" name="auth_conturl" value="<?php echo $auth_conturl; ?>"/>
<?php echo form_close();?>
</div>
To use the current dynamic url as form action, just use -
<?= form_open(current_url()); ?>
I am using codeigniter and the tutorial from here. I have made a basic blog tool which works fine. However as it stands to add a new post you have to go to a separate page 'create.php' to get to the form. I would like to try and put the form on the same page as the page that will be updated i.e. 'index.php'. If I try to do this at the moment the form simply refreshes and does submit the data.
model
function insert_post($data){
$this->db->insert('posts', $data);
return;
}
Current View (admin/create.php)
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
View I would like the form to be on (index.php)
<?php
echo '<p>Welcome '.$username.'! All posts available for edit or deletion is listed below.</p><br/>';
echo anchor('admin/create','Create New Post');
$count = count($post['id']);
for ($i=0;$i<$count;$i++)
{
echo '<div class="postDiv">';
echo '<h4>'.$post['title'][$i];
echo '<p>'.$post['summary'][$i].'</p>';
echo '<p>'.$post['content'][$i].'</p>';
//echo anchor('blog/view/'.$post['id'][$i],' [view]');
echo anchor('admin/edit/'.$post['id'][$i],' [edit]');
echo anchor('admin/delete/'.$post['id'][$i],' [delete]</h4>');
echo '</div>';
}
?>
Controller
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $_POST;
$this->posts->insert_post($data);
redirect('admin');
}
}
This was straight forward when I used normal php but with codeigniter I am getting lost with the MVC stuff. I know this is probably a fairly basic question so please either explain your answer or give me a link to something which will explain what I need to do as I want to learn from this. I have read the codeigniter docs on validation but I dont think thats my problem?
What you are trying to do is called embedding a view. I will try to explain how but you should also check some links which might prove to be more in depth:
http://net.tutsplus.com/tutorials/php/an-introduction-to-views-templating-in-codeigniter/
Codeigniter: Best way to structure partial views
The crux of what you need to do is change the link on index.php from:
echo anchor('admin/create','Create New Post');
to
$this->load->view('admin/create');
Now this should work, but to help you on the MVC front, it helps to explain why doing it this way is wrong. The idea of MVC is to seperate the functions in your application into their distinct roles. Most people will frown at putting business logic into views unless it is very minimal. The way that we could improve upon your code is to load the view in the controller, and set it to variable.
At the bottom of the codeigniter docs for views it shows how to load into a variable:
http://ellislab.com/codeigniter/user-guide/general/views.html
if the third parameter of load->view is set to true then the function will return your view as a string instead of outputting it to the browser
$data['input_form'] = $this->load->view('admin/create', $data, true);
then in the view that you want to load that form all you need to do is echo input_form
<?php echo $input_form;?>
So that should solve your problem but there are also a few more things you can do in your view file that will improve the readability of your code.
Instead of using a count() and for loop you can use foreach which makes everything much easier
<?php foreach ($post as $post_item):?>
<div>
<h4><?php echo $post_item['title'];?></h4>
</div>
<?php endforeach;?>
It also helps to break your view files up and have more tags. It might seems like it is extra bloat, but when you have larger view files it will be very cumbersome to continue using as many echo's as you have
just add one method uri_string() in your form action, uri_string will take same url of page put in action you can submit form to same page
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="<?=uri_string()?>" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
in controller little chagnes
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $this->input->post();
$this->posts->insert_post($data);
redirect('admin');
}
}
Use session library
check this another stackoverflow thread to know how to use session
In order to use session library, u need to configure encryption_key in config.php
To do that, check this out
below is my 'mainview.php' view. from here iam attempting to submit and just open the next view which is called 'carerview.php'.
<form action="<?php echo base_url()?>login" method="post">
<div class="input-prepend">
<span class="add-on"><i class="icon-envelope"></i></span>
<input type="text" id="" name="" placeholder="your#email.com"></br></br>
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" id="" name="" placeholder="Password"></br></br>
<button type="submit" class="btn btn-primary"><i class="icon-user icon-white"></i>Sign in</button>
</div>
</div>
</form>
Iam trying to submit this is giving me issues.The Index page loads which contains the above view. but when i submit . i get requested URL not found on this server
. then if i use the full url action="application/controllers/user/login" i get a forbidden, dont have permission to access it.
my method in my controller class is just to load the next view on submit so i dont think there is an issue there . below is the controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function index()
{
if(!$this->isLoggedIn())
{
$this->load->view('mainview');
}
else
{
//do something
}
}
public function login()
{
$this->load->view('carerview');
}
public function isLoggedIn()
{
return false;
}
}
any help would be appreciated thanks.
if you didn't remove index.php from your URL and didn't set anything to base_url in configuration,try this
<?php echo base_url();?>index.php/user/login
localhost/your_app_folder/index.php/controller/action
Your form action is base_url(), which means is the application index route.
Try using form_open() (in the form_helper), which takes care of building the correct url:
<?php echo form_open('user/login');?>
... your form here
<?php echo form_close();?> // since I didn't see a close form tag in your form
Be careful of any routes that might intercept the request.
Alternatively, you could use site_url():
<form method="POST" action="<?php echo site_url('user/login');?>">
I'm having trouble getting the form validation library to send my form errors back to my form in this case.
I have a controller that handles uploading images called addImage.php. This controller only handles the do_upload processing. I have a view called uploadimage.php that contains the upload form and submits to /addImage/do_upload.
The upload form is loaded on the front page of my website using a template in code igniter using
<?php $this->load->view('uploadimage'); ?>
The front page controller is contained in home.php
Right now after validation fails, I'm just redirecting to the homepage which clearly doesn't load the errors back (in addImage.php)
if($this->_submit_validate() == FALSE)
{
redirect('/', 'location');
return;
}
How can I redirect to my template_front.php while keeping those errors. Can I somehow call my home.php controller from the uploadimage.php controller to do this? I've confused myself trying to explain it! If this is totally unclear, let me know and I'll try to clarify.
Per the Documentation, you are suppose to simply re-load the view file on failure.
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
a redirect generates a new server request which flushes the validation error information.
on validation failure you should reload the form. May be you want to add a button to concel uploading.
On the view, you should add some tag to show errors (there are lots of info about validation helpares) like in:
<?=form_open_multipart("/personas/savefoto", array('class' => "form3") )?>
<h3><?=$heading?></h3>
<div class="center">
<?php echo '<strong>'.mb_convert_case($record['nombre'].' '.$record['apellido1'].' '.$record['apellido2'], MB_CASE_TITLE).'</strong><br/>';
if( file_exists("fotos/e".MATRIZ."/b".$record['id'].".jpg")){
?>
<img class="foto" src="<?php echo base_url()."fotos/e".MATRIZ."/b".$record['id']?>.jpg"/>
<br/><br/>
<?php
} ?>
</div>
<div class="form-row">
<label for="imagen">Nueva imagen <br/>(jpg, gif o png)</label>
<input type="file" name="userfile" size="20" />
<br/>
<?php if(isset($error_image)) echo '<p class="error">'.$error_image.'</p>'; ?>
</div>
<div class="form-row center">
<input type="submit" value="Aceptar" />
<input type="button" value="Cancelar" onclick="location.href='/system.php/personas/admin';">
</div>
<?=form_close();?>
look for the if(isset($error_image))
You could utilize the validation_errors() function and set them to a session variable
$this->session->set_userdata(array('form_errors', validation_errors()));
then access them on your redirect page.
echo $this->session->userdata('form_errors');
$this->session->unset_userdata('form_errors'); // prevent them from being stored past use