How do you exit execution of a codeigniter program? - php

I am currently working on adding pre-validation to my website. So that pages that require a log-in or other criteria, will only display if your session matches that criteria. I've got most of the system working, but I have one major obstacle. I cannot figure out how to stop CodeIgniter from running the rest of the controller (and thereby showing the page anyways), when the validation fails.
Here is my configuration:
All my pages are in the Content controller
My security system is a model called security.php
In the _head private function (which is called by every page), I load security.php and call it's main function: run()
$this->security->run() gets the specific validation criteria for the page, and checks them.
If the user passes, then run() does nothing, and the page execution continues
This is where I need help. If the user does not pass, then I need to display an error page, and stop the controller from calling any other views.
Does anyone know how to do this?
Thanks,
Lemiant

You could do one of two things. A would be to redirect to another page with a differant uri. B would be to use an if/else statement to choose which view you show under the same uri.
One thing you need to do is have the security method you talked about return TRUE or FALSE if it is successful or not.
Examples:
A:
if(!$this->security->run())
{
redirect('my/error/page');
}
B:
if($this->security->run())
{
// Security Passes, proceed as normal
}
else
{
// Security Fails, show error page
}
Hope this helps

How stop execution of codeigniter: die(); or exit();
But, I don't think that's really what you want to do. What you want to do is to load a different view to show an error page if the validation fails.

Related

display a specific page only the 1st time user visite our site

I am working on darskite project in case of crisis. For this project we want to prepare a specific case.
We need to inform the user visiting our website of the crisis (eg : our factory has an electrical failure). We want to show him this specific page of information only during the first time he comes in our website. For the next visits, he must visit our classical homepage.
How can we target and identify a user to redirect him only once to the alert message (when he first logs in)? Are there any solutions like those for retargeting Google or Facebook via cookies? If Yes, what kind of cookie ?
Our website is powered by Drupal 7. Can Drupal handle this case?
Thank you for your ideas.
From the drupal docs:
https://api.drupal.org/api/drupal/modules!user!user.module/function/user_cookie_save/7.x
What you can do is: You first check if a cookie has been set. If not, then you set it. The next time the user visits your site, he/she will have a cookie so the logic gate will be passed.
Here's an example that you can use in your header file in drupal:
if (!isset($_COOKIE['some_descriptive_cookie_name'])) {
user_cookie_save('some_descriptive_cookie_name');
drupal_goto('temp/page/here', [], 307);
}
drupal_goto is documented here: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_goto/7.x
Good luck.
There are two approaches:
You can do it using the JavaScript's localstorage
You can do it using PHP's $_SESSION[' ']
Both will follow the same mechanism, when user loads the webpage for the first time, set a variable as true. Now for the next visits check this variable, if it is set to true, don't load the first page and redirect it to your classical page.
Drupal can handle almost everything.
What I would do is to create a boolean private field in the users profile to store if the user already saw that particular page.
Following this approach you can also make reports about how many users have seen that page, or know if a particular user saw that page. Using fields gives you a lot of power in Drupal.
How can you store this value when the user sees the page? Check the rules module and don't forget to active the rules UI so you can configure this action triggered by the mentioned condition.
You can use hook_user_login.
function MODULE_user_login(&$edit, $account) {
// The user has never logged in before.
if ($account->access == 0) {
// Redirect user when first login.
$_GET['destination'] = 'redirect_url';
}
}

Is there any reason to use another function to validate user input on a login screen whent he login screen is on the main page?

As I have right now, I have 3 functions: Main,Login and Panel. Explanation of the 3 functions:
Main
This is the home page. The thing is, on this page there is a login screen as well. So the input will be sent to the function 'Login'.
Login
This is where (only) all the validation will be. If validation fails, I'm sending it back to the Main with the error messages, and if it succeeds, It'll go further to the function 'Panel'.
Panel
Success. You logged in. Nothing special here.
Now my problem is, everything described in the function Login, can mostly fit in the Main function. Is there any reason to not just get everything from Login and put it in Main? So basically when the form is sent, if it fails, stay on the same page but with error messages or 'Succes! you logged in.' I feel like I'm overthinking this too much.
There should be no repetition, validation must be separate function for example validateData(Login) and similar (in calcFunctions.php)
HTML functions should be also in separate functions in for example (view)showFunctions.php then you proceed procedural in index.php you start with if session does not exists you do this else that.
Function login, main and similar are bad because I don't know what they are doing just by looking at their names. Functions you can use for example for particular actions in index.php. showInfoForEveryone, showInfoForLoggedIn, showSingupAndLogin, cleanData, showFormSingUP, showFormSingIn, errortable (array for errors that you can display if there is any), validateData() etc..
This way there is no repetition.

Codeigniter Model to Controller Flow

I get the MVC thing. :) I swear I do.
So, I have the main controller that serves up either the Home 'view' or a Login/Registration 'view' based on if the user is logged in.
Works fine and dandy.
On registration an email link is sent, which the user needs to click to verify the account->email, this happens to be a function in the Home controller that fires off a model is the link is valid.
Now, inside this model is the code to update the database with A: Activated/Not, B: Try Count.
Now, once this is done, I want to display the Login/Register 'view' with an appropriate message (failed, not failed, tried too many times, etc...)
I was going to use a redirect and throw the message type, and message text in a session variable and just display it that way, but then got to thinking that I could bypass that by firing off the Home controller index function passing in an array variable containing the message type, and message text.
Boy was I wrong.
So, how can I do this? I'd really like to stay away from relying on sessions
The respective method of Model should return a value (probably an array) that contains status and count (pseudo-code)
$statusCount = $model->getStatusCount($input);
And later pass the data to View
$view->set('statusCount', $statusCount);
So answering the question: yes, you can evade the $_SESSION.

Finish your previous task or my website will just reload the same page again

I want to detect if a particular php script has been run or if a particular form has been submitted, if that is true don't let the user go anywhere else on the site without finishing clicking submit buttons first! If you go back and want to refresh or if you want to click something else on my site, NO, no you can't because you didn't finish with your previous task and website will just reload the previous form or result for you and you have to click form button "Quit" or header link "Return home" to continue.
Reason I wan't this is because I am simulating a simple combat game with php and I don't know how to achieve this. Maybe with javascript?
I am even providing a picture to understand me better :) I really hope someone has a php or javascript solution for this.
Picture of what I am talkig about
EDIT: before you downvote atleast provide me with some tips where to look for the solution and do the research... I am lost, don't know what to search for
The simplest way that I would do this is to use a session variable and a single point of entry to the code.
If a single index.php file takes the user through the code and displays the output as needed, then I would simply use a variable within the session object to redirect the user to the same page until it was in a different state.
Something in your code like:
if ($_SESSION['in_combat'])
{
// redirect user back to the same page
}
else
{
// allow other action as requested by link clicked
}
Should do the trick, if the session is set to true then any action will redirect the user back to the page that needs their attention, otherwise, it will allow them to perform any action based on a link that they click.
Edit: By single point of entry, I mean that the code ALL functions off a single index.php page which then controls the further flow of the execution of the code. That index page will check for the various session variables, interpret and execute the various POST, GET requests and the like. A single point of entry is the best thing you can do when writing code that ensures your user is only able to perform the actions that they are supposed to perform.
Edit 2: First off, the single Point of Entry is a way to ensure that the PHP executes as you need it to - which means that ALL your HTML is displayed via a single PHP code. I normally do this by making a base index.php page that then directs the flow of execution depending on variables passed to it - whether they are in a session or post/get requests.
While it may not always be the most efficient way of doing it, I generally have a case statement that controls what is both displayed and executed depending on variables passed to the code.
If you already have a MVC set up, then this is the obvious place to control the execution of the page that is displayed to the user - this is obviously the index.php page itself.
As for the $_SESSION variable, this is now easy, put the control flow into the MVC while at the same time have the code that triggers it embedded within the execution path of your program. By that I mean something like this control flow:
if($_SESSION['inCombat'])
{
// This is where you redirect the user to code that ensures that the user cannot get out of the combat sequence if they are in it already.
}
else
{
// Normal Flow of execution...
}
if($hasInitiatedCombat)
// or something like the following:
// if($_REQUEST['startCombat']==true)
{
// This is where the code execution path leads to when combat is initiated.
$_SESSION['inCombat']==true;
}
With this simple code, whenever the person enters combat (or whatever) a session variable is set to TRUE then any link of page that they request checks this variable to determine what code the execute. If it is set to TRUE then the code automatically executes to ensure that they are still within the combat phase, rather than allowing them to simply click on a link to exit the current code execution path and go elsewhere.

How best to pass a message for the user between pages

So the chain of events is:
The user submits a form.
During the processing of the submission, there is a message generated, such as "Your record was saved."
The user is redirected to a new page, say the search results.
The new page needs to display the message.
So, the question is how to get the message from step 2 to step 3? This is only one simple example...there are many other much more complicated examples.
I am using PHP.
Needs:
supports multiple messages and need to be formatted on the receiving machine as required
messages can be added on the same page (such as within step 4)
messages added from inside any function or object
Some options I have come up with:
store in a session variable as an array and emptied after each display
pass as a get or query parameter; can get annoying as you are constantly processing this and have to remember to get it; as it can get long, it could easily go over the max length of the query string
store in the database on a per session basis (may not always be for a logged in user); this would require an extra insert on each page where they are added, possibly multiple, and an extra select on every page
Currently I have been storing the messages in the session in an array, but I'm wondering if there is a better way. I don't think the other 2 options above are very good.
Edit: I use 2 functions for the session method: AddStatusMsg() (adds an element to the array) and DisplayStatusMsg() (returns an HTML formatted message and empties the array).
I would recommend AGAINST storing these messages either in the database or in the session, for one simple reason: tabs. (Well, really, the stateless nature of HTTP.)
Think of a person who's got multiple tabs open of different sections of your website. This person performs some action and while that loads, switches to another tab and clicks on a link. If you're storing the messages in the session/database and the switched-to tab is a page that can display these messages too, the user has now entered a race condition where depending on which request the server responds to first, the messages may display where they were not intended.
Now, there are some situations where this legitimately might not matter, but it could also be extremely confusing in some cases.
Putting the messages in the request doesn't have to be as bad as it initially seems. Perhaps you could store all the messages you want to display in the database with a numeric (or, for bonus obfuscation, hash) ID, and pass a list of IDs in the query string. This keeps the query string short, and all you have to do is keep track of what ID corresponds to what message in your code.
I would stick with the session approach only perhaps adding support for this messaging system on the master page. You are on the right way as the all other approaches have a greater cost, of simplicity or performance.
I suppose you have a master page which is the template for all other pages. If you don't have it's a good reason to have one, so you don't need to take care of handling the displaying of the messages on every page you need it as long as you have a specific place to show them.
You can also use a specific div rendered by the master page for that and let the position be handled by the current page. If I understand correctly you need some kind of timing between the showing of the message and the user redirection to another page. This could be achieved using any AJAX library to show that div I said before and then redirecting to a new page.
I suggest taking a look into jQuery.
This is how I like to do it:
function set_message($message_type, $message)
{
$_SESSION['messages'][$message_type][] = $message
}
function get_messages()
{
$messages_array = $_SESSION['messages'];
unset($_SESSION['messages']);
return $messages_array;
}
where $message_type can be "warning", "error", "success", etc. and depending on the type you can show the user a different image/color/whatever.
This problem is a classic example of how to have data persist in a "stateless protocol" like http.
Your options are:
Pass it in the GET parameters (not
user friendly)
Store it in the DB
Store it in Session
Options 2) and 3) require the user to have a cookie (otherwise, there's no way to match the user to the message). Between them, I'd go with PHP's built in sessions. Simply set a session variable at your step 2, and have the search page always check for the variable in your step 4
Nothing to it. Don't over complicate things.
Probably the best way is to store it in the session. It's the simplest way and as John said, 'Don't over complicate things'.
Store it in the database as well as the session. This way the user can get to his history if he needs it, and you have easy access through the session data.
Don't use a query parameter, it'll only confuse the user at some point when the message is displayed when it shouldn't be.
Displaying the messages should be a part of your main template (in other words; done once).
Maybe a slight improvement would be to store, instead of an array, an object's instance that gets populated and knows how to display the messages appropriately, deleting the data itself after any display routine gets called. That way you don't have to repeat the display and delete logic everywhere, plus, you can code different output routines in the object depending on the need.
I think you're doing it the right way. You should stay away from the database for this and putting it in the URL is ugly. You could write a nice little class for this which can make it simpler.
Here's a little session class:
<?php class session
{
public function __construct()
{
session_start();
}
public function set($name, $value)
{
$_SESSION[$name] = $value;
}
public function get($name)
{
return (isset($_SESSION[$name])) ? $_SESSION[$name] : false ;
}
public function delete($name)
{
unset($_SESSION[$name]);
}
public function destroy()
{
$_SESSION = array();
#session_destory();
#session_regenerate_id();
}
}
A little message class can be built on that pretty easily.
I'm at this crossroad myself and I've considered all options extensively.
How about storing two browser
cookies, one called page and the
other called message.
On redirect you overwrite the cookie.
When the page loads you check if
said cookie exists (in the http
headers sent by the client).
Check if it's for that page, if it
is, store the message in a variable
and unset the cookies.
If it's not for that page, ignore
it, it will be output on the other
tab that is loading or if it is for
a page that for some reason never
unset the cookie it will eventually
expire.
This avoids using the database and session cookies.

Categories