Calling string in separate file in CodeIgniter - codeigniter

I'm building a profanity/racial slur filter for my website. I have it working, but my preg_match string is quite long. I'm just wondering if there is some way to host this long string in a separate file in CodeIgniter and then call it when I need to in the preg_match.
I have googled this and I couldn't find anything, so I thought I would ask here.
What I'm doing now is hosting my string in the model and then calling this:
if(preg_match($filterRegex)){
databaseStuffHere();
}

Here are a few options. Depending on how and where you are using this string and function, one may be better than the others.
Config
You could store the value as a config, in application/config/config.php
$config['filter_regex'] = 'yourReallyLongString';
The primary config is auto-loaded by CodeIgniter, so you can use it like so:
$filterRegex = $this->config->item('filter_regex');
if(preg_match($filterRegex, $subject))
{
databaseStuffHere();
}
Constant
If you're using this long string in several places and it would be useful to have global access, you could define it as as constant in application/config/constants.php. It will also prevent you from accidentally redefining the value.
define('FILTER_REGEX', 'yourReallyLongString');
Then use it with your function like this:
$filterRegex = FILTER_REGEX;
if(preg_match($filterRegex, $subject))
{
databaseStuffHere();
}
Helper
Finally, you could use a helper. You can load the helper when required, or auto-load it. You can create your own helper in application/helpers/. It could look something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('filter_slurs'))
{
function filter_slurs($subject = '')
{
$filter_regex = 'yourReallyLongString';
if (preg_match($filter_regex, $subject))
{
return FALSE;
}
else
{
return TRUE;
}
}
}
Having a function to handle this may make your code easier to follow and more meaningful, for example, in your controller, you could use it like this:
$this->load->helper('slur_filter_helper'); //assumes the helper file is: slur_filter_helper.php
if(filter_slurs($subject))
{
//do something
}
else
{
//do something else
}

You can use it with config file (system/application/config/config.php) to set configuration related variables.
====================== DEFINE WHAT YOU WANT in config.php ===========================
$config['REQUIRED_SRTING'] = 'YOUR_REQUIRED_LONG_STRING_OR_WHAT_YOU_WANT_STORE';
But best place to set constant is
(system/application/config/constants.php) to store site preference constants.
===================DEFINE WHAT YOU WANT in constants.php=========================
define('CONSTANT_STRING','YOUR_REQUIRED_LONG_STRING_OR_WHAT_YOU_WANT_STORE');

Related

CodeIgniter URI Routing: remove method name index from URL

I am working with CodeIgniter (V:2.2.6) and I have a simple class User with some basic methods like create, update, edit, delete and index. For the index function, I am using an argument $user (which is the second URI segment) in order to display some information regarding that user. So the default URL looks like:
/user/index/john
to display some information about the user 'john'.
Now, I want to remove the term 'index' from the URL, so that it looks like:
/user/john
For that purpose I have added the following rule in routes.php.
$route['user/(:any)'] = "user/index/$1";
It serves the purpose, but it prevents accessing other functions like /user/create and goes inside /user/index automatically. To solve this problem, I can not see any other way except manually adding routing rules like
$route['user/create'] = "user/create";
for each method of the User class, which is not cool at all. So, please can anyone suggest me a better way of routing under the current circumstances?
Here are my codes:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function index($user = '') {
echo "index!";
}
public function create() {
echo 'create!';
}
}
Note: I have gone through the CodeIgniter documentation for URI Routing and another similar question here, but could not figure out a promising solution. And please don't suggest for CodeIgniter version update.
I'm not sure, if this is the answer you like, but i think it should work.
Just put this function in your user controller.
public function _remap($method)
{
if (method_exists($this, $method))
{
$this->$method();
}
else
{
$this->index($method);
}
}

changing the url into dash instead of underscore using Codeigniter

Hi im using codeigniter framework because its really cool when it comes to MVC thing. I have a question regarding in the url thing. Usually when saving a controller, lets say in the about us page it has to do something like this About_us extends CI_Controller. When that comes to the url thing it goes like this test.com/about_us. I want that my url is not underscore. I want to be dashed something like this test.com/about-us. How will i able to use the dash instead of using underscore???
any help is greatly appreciated
thanks!
Code Ignitor 3 has this built-in option. In your routes.php:
$route['translate_uri_dashes'] = FALSE;
Just change this to "TRUE" and you can use either _ or - in URL
Here is a detailed article how to fix it.
You will just have to create routes for your pages, as far as I am aware, there is no config directive to change the separating character, or replace '-' with '_' in CI_Router, (probably wouldn't be too hard to add this).
To allow for '-' instead of '_':
Create a file in application/core/MY_Router.php
Change 'MY_' to whatever value is specified in your config directive: $config['subclass_prefix']
insert code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Router extends CI_Router {
function _set_request($segments = array()) {
if (isset($segments[0]))
$segments[0] = str_replace('-','_',$segments[0]);
if (isset($segments[1])) {
$segments[1] = str_replace('-','_',$segments[1]);
}
return parent::_set_request($segments);
}
}

PHP - Global Variables

I am trying to dynamically set database connection credentials based on who logs into a web page. I'm pretty sure it's not working because of the $connectdb variable not being defined. Can someone please check out my code and try to get it working? Thanks!
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$connectdb="";
class Main extends CI_Controller {
function __construct() {
parent::__construct();
echo $connectdb;
$this->load->database($connectdb);
$this->load->helper('url');
$this->load->library('grocery_CRUD');
}
public function index() {
if ($_POST["username"] == "root") {
global $connectdb="default";
}
if ($_POST["username"] == "user1") {
global $connectdb="user1";
}
if ($_POST["username"] == "user2") {
global $connectdb="user2";
}
$connect = #mysql_connect("localhost", $_POST["username"], $_POST["password"]);//won't display the warning if any.
if (!$connect) {
echo 'Server error. Please try again sometime. CON';
} else {
print("Employees");
echo "<br>";
print("Visitors");
}//Just an example to ensure that we get into the function
// LOAD LIBRARIES
}
public function employees() {
$this->grocery_crud->set_table('employees');
$output = $this->grocery_crud->render();
$this->_example_output($output);
}
public function visitors() {
$this->grocery_crud->set_table('visitors');
$output = $this->grocery_crud->render();
$this->_example_output($output);
}
function _example_output($output = null) {
$this->load->view('our_template.php',$output);
}
}
A quick read of THE MANUAL will show you it's pretty easy to have multiple database connections. You define the connection parameters in your database.php config file then call the database with the group name.
if($user == 'someguise'){
$this->load->database('guiseDB');
}
HTH
For something as important as this i would strongly suggest running the form input through CI form validation first. You really should be validating and doing things like limit the number of characters, make sure its letters only, trim whitespace and XSS cleaning - all before you do anything else. (this helps your user as well)
then to get the value from the form - do something like this
$username = $this->input->post( 'username', TRUE ) ;
and work with the one variable $username. the TRUE XSS cleans the value, and then instead of repeating
$_POST["username"] ==
over and over and over, you are just checking $username. also makes the code easier to read. if you need $username in different methods just use:
$this->username = $this->input->post( 'username', TRUE ) ;
and then $this->username will work in any method in the class.
finally consider having a table of users or config list -- and then use a different value to call your database. in other words maybe they log in with the user name: "root" but then its a different name like global $connectdb = "rootadmin"

CodeIgniter page caching with a exception

I like to use CodeIgniters page caching. But I've got a views counter in the controller, something like:
$this->db->query("UPDATE tb_product SET popularity=popularity+1 WHERE product_id=".$this->db->escape($this->uri->segment(2))."");
Is it possible to use page caching but make a exception to run this query only?
Yes. You could try to implement a hook. This would have to be the 'cache_override' hook. You could do the DB call from the hook.
http://ellislab.com/codeigniter/user-guide/general/hooks.html
Your hook method will have to call the original caching itself after doing the DB call.
function your_hook( )
{
// your DB code here
// Use some CI globals for this, see /system/core/Codeigniter.php
if ($OUT->_display_cache($CFG, $URI) == TRUE)
{
exit;
}
}
You could write a custom Output.php class and override (decorate) the original _display_cache method. Place your MY_Ouput.php in the /application/core directory and CI will use it automatically.
http://ellislab.com/codeigniter/user-guide/general/core_classes.html
Put something like this in it:
class MY_Output extends CI_Output
{
function _display_cache( &$CFG, &$URI )
{
// your DB call
// The original call
return parent::_display_cache( $CFG, $URI );
}
}
I didn't try this myself, but it should help you on your way. One of these will probably work. Good luck!
Thanks for your answer, but I've striped the counter out and wrote a cronjob which will get statistics from Google Analytics trough GAPI.

accessing lang variables from controller + codeigniter

How can I access my lang variables in controller?
function index()
{
$seo_title = $this->lang->line('blablabla');
$data['page_title'] = $seo_title;
$this->load->view('contact/index.php',$data);
}
in my lang file blablabla has string in, and it works well when I call from view file. but when I want to call from controller, it doesnt return anything :(
any idea about problem? appreciate!!
You need to load the language file you want to use before you grab lines from it:
$this->lang->load('filename', 'language');

Resources