one codeigniter application folder run two website with different domain - codeigniter

could i use one codeigniter framework directory to create multiple applications?
I have two website with one CodeIgniter application, i am used one DB for both of website, system folder, config, view, controller etc are also same.
main website is working fine, all links are working and another website only home page is working, rest of the links are not working, when i am open another link the error is occur: "Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid." version of codeigniter is 2.2.0, please help.
Thanks in advance

Try this:
ex:
- subdomain1.hostname.com
- subdomain2.hostname.com
then in my front index:
// Host address
$host = $_SERVER['HTTP_HOST'];
$SERVER_NAME = $_SERVER['SERVER_NAME'];
define('HOST', $SERVER_NAME);
// Extract eventual subdomain
$host3 = strrpos($host, '.');
$host2 = substr($host, 0, $host3);
$host1 = strrpos($host2, '.');
$subdomain = substr($host, 0, $host1);
if($host == 'localhost') {
define('HOST_TYPE', 'localhost');
define('SUBDOMAIN', FALSE);
} else {
if($subdomain !== 'www' && $subdomain !== '') {
define('HOST_TYPE', 'subdomain');
define('SUBDOMAIN', $subdomain);
} else {
define('HOST_TYPE', 'site');
define('SUBDOMAIN', FALSE);
}
}
in my config.php config:
switch (HOST_TYPE) {
case 'subdomain':
$config['base_url'] = 'http://'.SUBDOMAIN.'.hostname.com/';
break;
case 'localhost':
$config['base_url'] = 'http://localhost/devpage/';
break;
default:
//$config['base_url'] = 'http://mainpage.com/';
break;
}
in my database.php config:
...
$db['default']['hostname'] = 'localhost';
switch (HOST_TYPE) {
case 'subdomain':
$username;
$password;
$con=mysqli_connect("localhost","username_db","password_db","name_db");
$query = "SELECT * FROM subdomain_table WHERE subdomain_name = '".SUBDOMAIN."';" or die("Error in the consult.." . mysqli_error($con));
if ($result = mysqli_query($con, $query)) {
while($row = mysqli_fetch_array($result)) {
$username = $row["username"];
$password = $row["password"];
}
}else{
mysqli_close($con);
redirect('http://hostname.com'); //No sudomain found or error page
}
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_close($con);
}else{
}
mysqli_close($con);
$db['default']['database'] = 'db_prefix'.SUBDOMAIN;
$db['default']['username'] = 'username_prefix'.$usuario;
$db['default']['password'] = $password;
break;
case 'localhost':
$db['default']['database'] = 'local_dev_db_name';
$db['default']['username'] = 'some_username';
$db['default']['password'] = 'some_password';
break;
default:
redirect('http://mainpage.com');
break;
}
$db['default']['dbdriver'] = 'mysql';
...
finally the constants.php config:
//this one resolve all your links!!!!!
switch (HOST_TYPE) {
case 'subdomain':
define('URL','http://'.SUBDOMAIN.'.hostname.com/');
break;
case 'localhost':
define('URL','http://localhost/devpage/');
break;
default:
define('URL','http://mainpage.com/');
break;
}
I hope you find it useful

I think the answer by #avenda goes someway but as you've mentioned there is only 1x DB then there is no need to play around with that code.
I think your simplest solution in your config file is simply:
$config['base_url'] = $_SERVER['HTTP_HOST'];
And then in your routes file:
if ($_SERVER['HTTP_HOST'] == 'x'){
$routes['default_controller'] = 'xController';
} elseif ($_SERVER['HTTP_HOST'] == 'y'){
$routes['default_controller'] = 'yController';
}
Haven't tested it but have a similar need coming up on a project so will have to implement something similar.

Related

CodeIgniter 3 session regenerated after login in Firefox

After login, I set session with user id and some information. It works very well on Google Chrome.
But it is redirect to login page after login on Firefox. I don't know what is the problem. Furthermore, the strange issue is this is working well on my local server like 127.0.0.4. This redirect issue is occurred on live server(hostinger) and only on Firefox.
Here is my config.php
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'eq_session';
$config['sess_expiration'] = 7200;
$config['sess_encrypt_cookie'] = TRUE; // JFRH
$config['sess_table_name'] = 'eq_sessions'; // JFRH
// $config['sess_save_path'] = NULL;
$config['sess_save_path'] = FCPATH . 'public/sess';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
$config['sess_match_useragent'] = FALSE;
And this function is customized library for authentication.
public function sess_validate($redi = FALSE, $sess_upda = FALSE) {
$CI =& get_instance();
if ($CI->session->userdata('sess_id')) {
//Preguntar si la variable de sesiĆ³n 'usua' existe o si se requiere
//que los datos de la misma sean actualizados
if ((!$CI->session->userdata('usua')) || ($sess_upda == TRUE)) {
$this->__sess_update();
}
return TRUE;
} else {
if (!$redi) {
return FALSE;
} else {
print "<script> window.location.href = '". base_url('auth')."'; </script>";
}
}
}
I set session data in my Auth Controller like this.
$this->session->set_userdata('sess_id', $usua->id_usu);
$this->session->set_userdata('sess_na', $usua->nom_usu . " " . $usua->ape_usu);
$this->session->set_userdata('sess_log', $usua->log_usu);
I have tested with changed session path.
I have fixed this.
Here are my config.php.
$root = "http://".$_SERVER['HTTP_HOST'];
As you can see, I was set the root like above line.
It works on my local server but server protocol was https when I deploy this on server. It is a cause of this problem.
So I fixed this like this.
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === 0 ? 'https://' : 'http://';
$root = $protocol . $_SERVER["HTTP_HOST"];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $root;
Now, works fine.

Error Exception: Indirect modification of overloaded property laravel

I'm making an API that store a new version of an application. Here is my code:
public function saveNewVersion() {
$artifact_url = Input::get('url');
$artifact_id = Input::get('id');
$artifact_name = Input::get('name');
$artifact_version = Input::get('version');
$urls = explode('/', $artifact_url);
//Exploding URL to dir
$app_dir = "";
for($i=5; $i<sizeof($urls); $i++)
$app_dir .= $urls[$i] . '/';
$app_dir .= $artifact_id;
//Checking if the artifact_id exists in the database
$app = Applications::where('app_dir', '=', $app_dir);
if (!$app->count()) {
//Save it as new application
$new_app = new Applications();
$new_app->application->name = $artifact_name;
$new_app->app_dir = $app_dir;
$new_app->save();
$app_id = Applications::where('app_dir', '=', $app_dir)->first()->id;
} else {
$app_id = $app->first()->id;
//Checking if the application name is not same as newrelic (Optional)
if ($app->first()->application_name != $artifact_name) {
$app = $app->first();
$app->application_name = $artifact_name;
$app->save();
}
}
//check if the last version exists in the database
$version = Versions::where('application_id', '=', $app_id)->orderBy('id', 'desc');
$lastVersion = $version->first()->version_number;
if ($lastVersion != $artifact_version) {
//check if the new version is exists before
$flag = 0;
$versions = Versions::where('application_id', '=', $app_id)->orderBy('id', 'desc')->get();
foreach ($versions as $item) {
if ($item->version_number == $artifact_version) {
$flag = 1;
break;
}
}
if (!$flag) {
$version = new Versions();
$version->application_id = $app_id;
$version->version_number = $artifact_version;
$version->save();
echo 'Application' . $app_id . 'has been updated to version ' . $artifact_version;
}
}
}
When I call the API using postman, the API runs successfully and stores the new version of the application. But when I'm using CURL. I got ErrorException: Indirect modification of overloaded property App\Applications::$application and it points to my $new_app->save() code.
Is there any problem with my code ? Or are there some parameters used in postman that make this error invisible ?
I may be wrong here but it looks like the issue is the issue is here:
$new_app->application->name = $artifact_name;
I think it should be:
$new_app->application_name = $artifact_name;
based on the other code.

joomla - router change url when getting the name of product

I have build my own component in joomla and client wants now a friendly urls f.e
website.com/someplace/{product-id}-{product-name}. So i Build my own router like this.
function componentBuildRoute(&$query)
{
$segments = [];
if (isset($query['view'])) {
$segments[] = "szkolenie";
unset($query['view']);
}
if (isset($query['product_id'])) {
$productName = JFilterOutput::stringURLSafe(strtolower(getProductName($query['product_id'])));
$newName = $query['product_id'] . '-' . $productName;
$segments[] = $newName;
unset($query['product_id']);
}
return $segments;
}
and parse route function
function componentParseRoute($segments)
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$item =& $menu->getActive();
$count = count($segments);
switch ($item->query['view']) {
case 'catalogue' : {
$view = 'training';
$id = $segments[1];
}
break;
}
$data = [
'view' => $view,
'product_id' => $id
];
return $data;
}
While on the end of buildroute function segments are ok I have exactly what I want that on the beginning of parse route I have something like
website.com/szkolenie/1-krakow <-- I dont know wtf is this krakow( I know it is city i Poland) but still where is it get from ? The getProductName function implementation is
function getProductName($productId)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('#__component_training.id as id, #__component_product' . name)
->from($db->quoteName('#__component_training'))
->where('#__s4edu_product.product_id = ' . $productId)
->leftJoin('#__component_product ON
#__component_training.product_id=#__component_product.product_id');
$training = $db->loadObject();
return trim($training->name);
}
So taking all this into consideration I think that something is happening between the buildRoute and parseRoute, something what filters the $segment[1] variable, but how to disable that and why is it happening ?
P.S
Please do not send me to https://docs.joomla.org/Joomla_Routes_%26_SEF
I already know all the tutorials on joomla website which contains anything with sef.
P.S.S
It is built on joomla 3.7.0
You do not have a product named "krakow" ?
If not you can try to remove the $productName from the build function, just to check if this "krakow" is added automaticaly or it's from the getProductName() function.
Also i noticed that you have an error i guess in the function getProductName()
->where('#__s4edu_product.product_id = ' . $productId)
It's should be
->where('#__component_product.product_id = ' . $productId)

Can't use database library in CI

For some reason I can't get the database library to work. Any time I put the line $this->load->database(); the script stops executing without returning any errors.
This is my database.php:
$db['default']['hostname'] = '127.0.0.1';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'employee';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
This is my model:
class Customers_model extends CI_Model
{
function __construct()
{
parent::__construct();
//$this->load->database();
}
function add_customer($data)
{
echo "BEFORE CHECK";
$this->load->database();
echo "OK";
}
}
As I said, it doesn't return any errors. So in this case the screen will return "BEFORE CHECK" but it wont: "OK". Any ideas?
Try to change persistent connection $db['default']['pconnect'] = TRUE; to $db['default']['pconnect'] = FALSE; Or you can enable error log in config file from $config['log_threshold'] = 4; where Threshold options :
0 = Disables logging, Error logging TURNED OFF
1 = Error Messages (including PHP errors)
2 = Debug Messages
3 = Informational Messages
4 = All Messages
Make sure that you have 'error_reporting = E_ALL' in your php.ini to display any errors that occurs.
After that, if you have wrong credentials you should see the error type.
In CodeIgniter (CI) is very easy to work with Database.
See:
http://ellislab.com/codeigniter/user-guide/database/examples.html
Try changing
$db['default']['hostname'] = '127.0.0.1';
to
$db['default']['hostname'] = 'localhost';
make sure for the password as well
Ok, so it looks like everything started working fine as soon as I uncommented this line in php.ini: extension=php_mysql.dll
However why it was not returning any errors in CI ?
Are you sure you are in "development" mode? (look at the beginning of the index.php)
What happens if you manually trigger an error? trigger_error('blah blah', E_USER_ERROR);
edit: The problem may be because CodeIgniter masks many SQL-related errors (for instance see this recent issue). The easiest solution to debug your code would be to install Xdebug and enable the scream option.

Error 500 "View Not Found" when using SEF and URL Rewriting

I am writing a custom component. I have the view employees. Under this view, I have two layouts, default and modal.
I have a menu item in the toplevel of the main menu, Employees that points to my employee view:
index.php?option=com_mycomponent&view=employees which resolves to domain.com/joomla/employees and displayes the default view as expected.
Now, inside my component I want to link to the modal view, and I do so using JRoute and this url:
index.php?option=com_mycomponent&view=employees&layout=modal
Which resolves to
domain.com/joomla/employees/modal
And produces this error:
500 - View not found [name, type, prefix]: modal, html,
mycomponentView
If I visit index.php using index.php?option=com_mycomponent&view=employees&layout=modal my modal view is displayed.
I have also found that visiting domain.com/joomla/employees/employees/modal displays the correct layout. It is as if joomla is forgetting what view is associated with the menu item at /joomla/employees, and instead looks for the view "modal" unless the extra "employees" is provided in the url.
Also worth noting, domain.com/joomla/employee?layout=modal works fine as well.
Here is what I have for my router.php. This was file was generated for me using the component generator at j-cook.pro.
<?php
defined('_JEXEC') or die;
function MycomponentBuildRoute(&$query){
$segments = array();
if(isset($query['view']))
{
$view = $query['view'];
$segments[] = $view;
unset( $query['view'] );
}
if(isset($query['layout']))
{
$segments[] = $query['layout'];
unset( $query['layout'] );
}
if(isset($query['id']))
{
if(in_array($view, array('edit','view','view','editfacility','view','edit','client','editclient','viewposition','editposition','edit','view','edit','view','view','edit','view','edit','view','edit','view','edit')))
{
$segments[] = (is_array($query['id'])?implode(',', $query['id']):$query['id']);
unset( $query['id'] );
}
};
return $segments;
}
function MycomponentParseRoute($segments)
{
$vars = array();
$vars['view'] = $segments[0];
$nextPos = 1;
if (isset($segments[$nextPos]))
{
$vars['layout'] = $segments[$nextPos];
$nextPos++;
}
if(in_array($vars['view'], array('edit','view','view','editfacility','view','edit','client','editclient','viewposition','editposition','edit','view','edit','view','view','edit','view','edit','view','edit','view','edit'))
&& isset($segments[$nextPos]))
{
$slug = $segments[$nextPos];
$id = explode( ':', $slug );
$vars['id'] = (int) $id[0];
$nextPos++;
}
return $vars;
}
So it is hard to provide an exact answer for this without knowing all the different ways that you want to have urls be parsed. But I will try to give a hint at what will solve this present situation (without hopefully introducing too many new issues!)
The basic issue is that the BuildRoute side does not get a view value so it is not included in the url. On the one hand it is not necessary, because it is in the menu. But it makes it a little harder to parse, so option one is to force there to be a view if you can by changing the top function to start like this:
function MycomponentBuildRoute(&$query){
$segments = array();
if(isset($query['view']))
{
$view = $query['view'];
$segments[] = $view;
unset( $query['view'] );
}
else
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$active = $menu->getActive();
if ($view = $active->query['view']) {
$segments[] = $view;
}
}
...
In this way, if there is a menu item for this and it has a view we will tack it on. This should generate domain.com/joomla/employees/employees/modal.
You could also probably do this logic on the parse side too. This would go instead of the other option above:
function MycomponentParseRoute($segments)
{
$vars = array();
$app = JFactory::getApplication();
$menu = $app->getMenu();
$active = $menu->getActive();
if ($active->query['view']) {
$vars['layout'] = $segments[0];
$nextPos = 1;
} else {
$vars['view'] = $segments[0];
$nextPos = 1;
if (isset($segments[$nextPos]))
{
$vars['layout'] = $segments[$nextPos];
$nextPos++;
}
}
... continue with final check for id
I would probably use the second option but both are an option. By the way, you are also likely to run into issues if you try to use an id without setting a layout.

Resources