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()); ?>
Related
EDIT: Problem fixed. I appreciate the replies I got, both for their help and the rapid response they was. The two answers I got was both rather identical, but I chose one of them to mark it as solved.
I have, for some time tried to get this to work but I can't and thus I am coming here, hoping for help.
I am currently trying to create a login, register and comment function on my website. Registering is working, logging in with those credentials also work, and I have got a filter to prevent empty-field entries.
Once I log in I have it echo out the possibility to go to the comment page, and my plan there is to allow the users to write a comment, see the comments below, and the author name will be grabbed from their login username. See where I am going? That is exactly what's not working, though. I can't get it to grab the username from the login field, and I am quite sure it has something to do with that the website doesn't remember the login, and I'm unsure how to set cookies and such if thats where the fix would be.
So, TL;DR - How do I get the website to remember a login, then insert it into a field?
Above the code is the website design itself, connection with the database, and session_start();.
Login.php code
<?php
if(!isset($_POST['submit_login'])) {
// Checks whether anyone have clicked the submit button, as long as they don't, show the form
echo '
<div class="loginform">
<h2>Please login to continue</h2>
<br />
<form action="login.php" method="POST">
Username : <input type="text" name="username_login"><br />
Password : <input type="password" name="password_login"><br />
<br />
<input type="submit" name="submit_login" value="Submit">
</form>
</div>
';
}
if(isset($_POST['submit_login'])) {
// Checks whether they have clicked on the submit button or not, if they have, check if the fields are filled or empty, as well as check it with the database.
$username_login = $_POST['username_login'];
$password_login = $_POST['password_login'];
$loginCmd = "SELECT * FROM tblUsers WHERE username='$username_login' AND password='$password_login'";
$result = mysql_query($loginCmd);
if(empty($username_login)) {
echo "<center>Wrong username.</center>";
}
else if (empty($password_login)) {
echo "<center>Wrong password.</center>";
}
else if (mysql_num_rows($result) == 0) {
echo "<center>User does not exist.</center>";
}
else {
mysql_query($loginCmd);
echo '<center>Logged in. Welcome '.$username_login.' !</center> <br />';
echo '<center>View/post comments here</center>';
}
Comments.php code
<div class="commentform">
<h2>View and post comments and thoughts here!</h2>
<p>All fields required</p><br /><br />
<form action="comments.php" method="POST">
Author : <input readonly type="text" name="author" value=''> <br /><br />
Comment : <textarea name="comment" class="insertcomment"></textarea><br />
<br />
<input type="submit" name="submit" value="Submit">
</form>
</div>
<br />
<hr>
<br />
<?php
if(isset($_POST['submit'])) {
// Checks if they have clicked on the submit button, if they have, send it to the database
$comment = $_POST['comment'];
$author = $_POST['author'];
$insertComment = "INSERT INTO tblComments(comments, author) VALUES ('$comment', '$author')";
if(empty($comment)) {
echo "<center>No text found in comment field.</center>";
}
else if(mysql_query($insertComment) ) {
echo "<center>Comment posted</center>";
}
}
Once you validate the login then you can store the username in a session array which is persistent between pages :
<?php
// this goes on top of the php page where ever you want to use session variable
session_start();
//once user login is valid then you can store username like this
$_SESSION["username"]=$username; //$username is what you used while validating the login
?>
On some other page you can get this value back as long as you have session_start on top:
<?php
//2 nd page
session_start();
echo $_SESSION["username"];//This will print username which you stored while logging
?>
For more information on sessions visit w3schools or php.net
You have two options to store the username between pages: Cookies, which are stored on the user's computer, or sessions, which are stored on your server. Consider sessions for any security-based authentication as cookies can be easily manipulated by your users.
Cookies:
$expiry_time = time() + 604800; // Expire in 7 days (time is in seconds)
setcookie("username", "administrator", $expiry_time); // set the cookie
echo $_COOKIE["username"]; // read the cookie
Sessions:
session_start();
$_SESSION["username"] = "administrator"; // set the session variable
echo $_SESSION["username"]; // read the session variable
My host company created a redirect in my htaccess file so that all of my pages are using my SSL cert and display as https. Since they did this I am unable to login to my site on the first attempt. It redirects me to my index.php page and starts a new session. Before doing this redirect, my session would carry forward when signing on. Which I need as I am designing an ecommerce website and want the items in the cart to move forward if they sign in.
htaccess file
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
Sign in page that redirects to my Signed-in index page. As you can see there is not a redirect on this to index.php...only the signed in index or an error would display. Something is causing the htaccess file to redirect me to my index page and start the new session. The thing is after I have attempted to sign in for the first time, the google chrome remember password feature displays, but I'm not logged in. When I try to login after I'm redirected, it allows me.
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
if($login) {
Redirect::to('indexSignedIn.php');
} else {
$tryagain = "The information you entered did not match our records.";
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
My sign in page form..
<?php
if(Session::exists('home')) {
echo '<p>' . Session::flash('home') . '</p>';
}
?>
<form class="signinform" name="Sign In" action="" method="post" autocomplete="on" accept-charset= "utf-8">
<span class="spancenter"><h1>Sign In</h1></span>
<hr><br>
<div class="centerleft">
<label for="username">Username</label>
<input type="text" name="username" class="biginputbar" autocomplete="on" required>
</div>
<div class="field">
<label for="password">Password</label>
<input type="password" name="password" class="biginputbarp" autocomplete="off" required>
</div>
<div class="field">
<label for="remember">
<input type="checkbox" name="remember" id="remember"> Remember me
</label>
</div><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<label for="widebutton">
<input id="widebutton" type="submit" value="Sign In">
</label><br><br>
The session flash you see in there was never an issue before doing the https redirect, so I'm not sure if that has anything to do with it?
Every page on my site displays as https. The weird thing about all of this is say if you added products to the cart. Then tried to login, it creates a new session and takes you back to the index.php page. Then when you try logging in again it sends you through. But say I log out and close the browser or at least the website from the browser. Then if I enter my websites address in again and re-visit the page, my first session is still present reflecting the products I added to the cart.
I then thought because of the new session being created that it may have something to do with my Cookie or Token Class. If not please ignore this, but I want to post any possible scenarios that may cause this
Cookie class
public static function get($name) {
return $_COOKIE[$name];
}
public static function put($name, $value, $expiry) {
if(setcookie($name, $value, time() + $expiry, '/')) {
return true;
}
return false;
}
public static function delete($name) {
self::put($name, '', time() - 1);
}
}
?>
token class
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)) {
Session::delete($tokenName);
return true;
}
return false;
}
}
?>
Added network log from trying to login..
Navigated to https://www.example.com/signin.php
Navigated to https://example.com/index.php
index.php:143 Resource interpreted as Image but transferred with MIME type
text/html: "https://example.com/productpics/".
Navigated to https://example.com/signin.php
Navigated to https://example.com/indexadmin.php
indexadmin.php:125 Resource interpreted as Image but transferred with MIME type text/html: "https://example.com/productpics/".
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
I am new to PHP Codeigniter framework. I am designing a page in which I am using a link. On clicking the link it is calling a jquery function, which submits form through jquery. I have used codeigniter form validation methods for server side validation and for the timebeing I have disabled the client side validation.
The problem is that in this process when the form is submitted through jquery, the codeigniter form validation method is not working.
But if I am using a submit button to submit the form then the codeigniter form validation method works perfectly.
Please advise me what to do if I need to submit the form through jquery and use the codeigniter form validation method.
Please find the code below:
Login Form:
<?php echo validation_errors(); ?>
<form name="login-form" id="login-form" method="post" action="<?php echo base_url();?>index.php/login/login_form" >
<H2>Login</H2>
<div id="login-box-name">
Email:
</div>
<div id="login-box-field">
<input name="user-name" id="user-name" class="form-login" title="Please Enter Correct User Name" value="" size="30" maxlength="2048" />
</div>
<div id="login-box-name">
Password:
</div>
<div id="login-box-field">
<input name="password" id="password" type="password" class="form-login" title="Please Enter Correct Password" value="" size="30" maxlength="2048" />
</div>
<br />
<span class="login-box-options">
<input type="checkbox" name="1" value="1" title="Want this computer to remember you!!"> Remember Me Forgot password?
</span>
<br />
<br />
<a href="" id="login-submit">
<img src="<?php echo base_url();?>assets/images/login-btn.png" width="110" height="40" style="margin-left:90px;" />
</a>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
jquery function to submit the form on clicking the "link":
$("#login-submit").click(function()
{
$('#login-form').submit();
return false;
});
Controller function:
public function login_form()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$data['title'] = 'Log In';
$data['errorMessage'] = '';
$this->form_validation->set_rules('user-name', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('login', $data);
$this->load->view('templates/footer');
}
else
{
$this->load->view('templates/header', $data);
$this->load->view('templates/menu');
$this->load->view('index', $data);
$this->load->view('templates/footer');
}
}
Here if I click on the "Submit button of the form, then the codeigniter validation works for user-name and password fields. But if I click the link with id="login-submit", then it calls the jquery function and the form get submitted. But the codeigniter validation does not work for user-name and password fields this time.
I need to submit the form through the link and the codeigniter validation function should work for this.
Thanks in Advance.....
Use .preventDefault() instead of just returning false on the anchor click event.
This has happened to me before and it seems to me that there is a conflict somewhere using .submit() inside a click event and returning false to stop the anchor's default behavior.
The code above is working fine. Actually I made a silly mistake in my code.
I used following code for jQuery and it is working now.
$("#login-submit").click(function(e) {
e.preventDefault();
$('#login-form').submit();
});
Thanks
it happens because it calls the function all the time when clicking on the button. you need to stop that.
$("#login-submit").click(function(e){
e.preventDefault();
$('#login-form').submit();
});
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