Codeigniter - Page cache with subdomains - codeigniter

I am using the default Codeigniter page cache e.g.:
$this->output->cache(n);
My problem is that I am using this within two different controllers and getting a duplicate cached page i.e. the same page being returned for both. I believe this is due to using a subdomain e.g:
mobile.mysite.com => Controller 1
mysite.com => Controller 2
When I enable the cache on both, i get the same page returned.
How can I generate a different cache for each?
Regards, Ben.

By default the output cache is controller based. So as you see if a controller is named the same then it will generate or use the same cache (if you cache directory is the same in both places).
Your best workaround is using the cache driver and storing your cache manually. Here is an example of the controller code:
public function index()
{
// If we have a cache just return it and be done.
if ($mobile = $this->cache->get('page_mobile') AND $this->agent->is_mobile())
{
$this->output->set_output($mobile);
return TRUE;
}
elseif ($page = $this->cache->get('page))
{
$this->output->set_output($page);
return TRUE;
}
$vars = array();
// Save a cache and output the page.
if ($this->template->is_mobile)
{
$home = $this->load->view('page_mobile', $vars, TRUE);
$this->cache->save('controller_mobile', $home, 500);
$this->output->set_output($home);
}
else
{
$home = $this->load->view('page', $vars, TRUE);
$this->cache->save('controller', $home, 500);
$this->output->set_output($home);
}
}

Related

TYPO3: clear cache of a page when file metadata is changed

I have a custom plugin which shows files for download based on sys_category.
When an editor changes the meta data of a file, e.g. changes the title or category, the changes are only reflected in the frontend when the complete frontend cache is cleared.
I've tried to add this to page TSconfig:
[page|uid = 0]
TCEMAIN.clearCacheCmd = 17
[global]
But this doesn't work. Any other idea how to clear the cache, when a sys_file_metadata record is changed?
Here is my solution. Thx Aristeidis for the hint.
ext_localconf.php
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass']['my_extension_key'] =
\Vendor\ExtKey\Hooks\DataHandler::class;
Classes/Hooks/DataHandler.php
<?php
namespace Vendor\ExtKey\Hooks;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Utility\GeneralUtility;
class DataHandler
{
public function processDatamap_afterDatabaseOperations(
$status,
$table,
$recordUid,
array $fields,
\TYPO3\CMS\Core\DataHandling\DataHandler $parentObject
) {
if ($table === 'sys_file_metadata') {
// hardcoded list of page uids to clear
$pageIdsToClear = [17];
if (!is_array($pageIdsToClear)) {
$pageIdsToClear = [(int)$pageIdsToClear];
}
$tags = array_map(function ($item) {
return 'pageId_' . $item;
}, $pageIdsToClear);
GeneralUtility::makeInstance(CacheManager::class)->flushCachesInGroupByTags('pages', $tags);
}
}
}
Of course this could be improved more:
Currently the list of page uids is hardcoded. That could be made configureable via extension manager settings.
A check could be implemented to only delete the cache if the file has a certain sys_category assigned, e.g. Downloads
But for the moment this solution is enough for my needs.

PHP and session

I have strange problem with sessions. In my small admin panel for my site there were some pages, 6 in fact. All worked nice. But in time I added one more page and when I go to that one firstly I see the content and after refreshing page or going to another one I'm thrown out from the account. Cookies are not deleted. It seems that session is destroyed but there is no any work with sessions. That is just infomartion page where some data from db is displayed.
This is code from index.php where session starts:
ini_set('session.gc_maxlifetime', 3600);
ini_set('session.cookie_lifetime', 3600);
session_start();
...
And this code from problem page 'orders.php':
$res = $administrator->getOrders();
while($order = mysql_fetch_array($res, MYSQL_ASSOC)) {
filtrate and print data from db in a table
}
Do you have any assumptions? I have not, was searching for an error for 2 days ;(
Check authorization function:
public function checkLogin() {
if(isset($_SESSION['hash']) && isset($_SESSION['id'])) {
$id = intval($_SESSION['id']);
$where = "`id`='$id'";
$cookie = DBWorking::getFieldWhere('cookie', 'users', $where);
$hash = mysql_fetch_assoc($cookie);
if($_SESSION['hash'] === $hash['cookie']) {
return true;
}
}
return false;
}

Codeigniter Page cache with GET parameter

I am newbie to CI cache. I am facing some weird problem with codeigniter page caching. $this->output->cache(300);
I was expecting that cached version would not load if arguments in GET[] would change. But it is loading cache without considering any GET[] parameters.
I have one page where it says whether comment has been saved or not [via get parameter],
/product/product-name/?saved=true redirecting to same page where comment form is located. But it is not working. How can i invalidate old cache and create new one depending upon the get parameter? or i need to change the behavior of my comment system?
Thanks.
EDIT
Should i simply use database cache instead of Web page cache in this case?
You just have to enable the cache_query_string option in the config/config.php file.
$config['cache_query_string'] = TRUE;
Create a cache_override hook to check if there are any GET[] variables set and then skip the cache_override.
[EDIT #1]
Here is an example:
Create this file in your hooks directory:
<?php
class GetChecker {
public function checkForGet()
{
global $OUT, $CFG, $URI;
if (isset($_GET) AND ! empty($_GET))
{
return;
}
if ($OUT->_display_cache($CFG, $URI) == TRUE)
{
exit;
}
}
}
Then add this to the config/hooks.php:
$hook['cache_override'][] = array(
'class' => 'GetChecker',
'function' => 'checkForGet',
'filename' => 'GetChecker.php',
'filepath' => 'hooks'
);
I haven't tested it, it might need a little tweaking to work...
I test on CI 3+ , file system/core/Output.php 559 line, change this
if ($CI->config->item('cache_query_string') && !empty($_SERVER['QUERY_STRING']))
{
$uri .= '?'.$_SERVER['QUERY_STRING'];
}
on this
if ($CI->config->item('cache_query_string') /* && ! empty($_SERVER['QUERY_STRING']) */ && !empty($_REQUEST))
{
// $uri .= '?'.$_SERVER['QUERY_STRING'];
$uri .= '?'.http_build_query($_REQUEST);
}
And add string to your application/config/config.php
$config['cache_query_string'] = true;
it will be work with GET, POST, COOKIE ....
If need only GET, just $config['cache_query_string'] = true; - enough
I found no easier way using Hooks to prevent writing cache, as its calling _write_cache() inside the _display() method itself of CI_Output class.
For quick and easiest solution I added two conditions to display cache and write cache, if Query String parameter has variable defined( offset in my case, as I wanted for pagination)
Edit: system/core/Output.php
Add Condition to prevent writing cache, if specific GET parameter found:
function _write_cache($output)
{
if (isset($_GET['offset']) AND ! empty($_GET['offset']))
{
log_message('debug', " Don't write cache please. As as its matching condition");
return;
}
...
...
}
Add Condition to prevent displaying cache, if specific GET parameter found:
function _display_cache(&$CFG, &$URI)
{
if (isset($_GET['offset']) AND ! empty($_GET['offset']))
{
log_message('debug', " Don't display cache please. As as its matching condition");
return FALSE;
}
...
...
}

CodeIgniter - dynamic pages - default controller url

edit
my solution in routes.php:
$route['news'] = 'news_controller';
$route['gallery'] = 'gallery_controller';
$route['(:any)'] = 'sites/$1';
and in my site conroller:
function index($site_id = '') {
//sanitize $site_id.
$this->site = $this->sites_model->get_site($site_id);
//etc.
}
THX to YAN
question:
so i wrote a little CMS with CodeIgniter. The admin can create sites. the site opens automatically when the segment of the url is like one in the DB. eg mysite.com/sites/about will call the "About" site. this works fine.
now i got a problem with my URL. i want this url
http://www.mysite.com/sites/about
turns to this:
http://www.mysite.com/about
the problem is, that i cannot use the routes.php and set wildcards for each site. (because they are dynamic and i dont know wich site the customer will create - and i dont want to edit the routes.php file for each site he will create - this should be done automatically)
the problem is i got other fix controllers too, like news, gallery or contact:
mysite.com/news, mysite.com/gallery, ...they work fine
so here is my Site Controller:
class Sites extends Public_Controller {
public $site;
public $url_segment;
public function _remap($method)
{
$this->url_segment = $this->uri->segment(2);
$this->load->model('sites_model');
$this->site = $this->sites_model->get_site($this->url_segment);
if($this->site !== FALSE)
{
$this->show_site($this->site);
}
else
{
show_404($this->url_segment);
}
}
public function show_site($data)
{
$this->template->set('site', FALSE);
$this->template->set('site_title', $data['name']);
$this->template->set('content',$data['content']);
$this->template->load('public/template','sites/sites_view', $data);
}}
and this is the Site_model who checks the database...if the url_segment fits the title in the DB:
class Sites_model extends CI_Model {
public function get_site($site_url)
{
if($site_url != ""){
$this->db->where('name', $site_url);
$query = $this->db->get('sites', 1);
if($query->num_rows() > 0){
return $query->row_array();
}
else
{
return FALSE;
}
}else{
return FALSE;
}
} }
i think i need something who checks if the controller exists (the first segment of the url) when not call the Site controller and check if the site is in the DB and when this is false then call 404.
any suggestions how this can be solved?
btw: sry for my english
regards GN
You can handle routes.php in the following way, just keep the (:any) value last:
$route['news'] = 'news_controller';
$route['gallery'] = 'gallery_controller';
$route['(:any)'] = 'sites/$1';
In your sites controller route to the specific site using the data from the URL.
function index($site_id = '') {
//sanitize $site_id.
$this->site = $this->sites_model->get_site($site_id);
//etc.
}
I am having trouble understanding the full intent of the question, but, from what I can tell, don't you simply need to add:
if ($this->uri->segment(1) != 'sites')
... // handle malformed URL

Codeigniter - best routes configuration for CMS?

I would like to create a custom CMS within Codeigniter, and I need a mechanism to route general pages to a default controller - for instance:
mydomain.com/about
mydomain.com/services/maintenance
These would be routed through my pagehandler controller. The default routing behaviour in Codeigniter is of course to route to a matching controller and method, so with the above examples it would require an About controller and a Services controller. This is obviously not a practical or even sensible approach.
I've seen the following solution to place in routes.php:
$route['^(?!admin|products).*'] = "pagehandler/$0";
But this poses it's own problems I believe. For example, it simply looks for "products" in the request uri and if found routes to the Products controller - but what if we have services/products as a CMS page? Does this not then get routed to the products controller?
Is there a perfect approach to this? I don't wish to have a routing where all CMS content is prefixed with the controller name, but I also need to be able to generically override the routing for other controllers.
If you use CodeIgniter 2.0 (which has been stable enough to use for months) then you can use:
$route['404_override'] = 'pages';
This will send anything that isn't a controller, method or valid route to your pages controller. Then you can use whatever PHP you like to either show the page or show a much nicer 404 page.
Read me guide explaining how you upgrade to CodeIgniter 2.0. Also, you might be interested in using an existing CMS such as PyroCMS which is now nearing the final v1.0 and has a massive following.
You are in luck. I am developing a CMS myself and it took me ages to find a viable solution to this. Let me explain myself to make sure that we are on the same page here, but I am fairly certain that we area.
Your URLS can be formatted the following ways:
http://www.mydomain.com/about - a top level page with no category
http://www.mydomain.com/services/maintenance - a page with a parent category
http://www.mydomain.com/services/maintenace/server-maintenance - a page with a category and sub category.
In my pages controller I am using the _remap function that basically captures all requests to your controllers and lets you do what you want with them.
Here is my code, commented for your convenience:
<?php
class Pages extends Controller {
// Captures all calls to this controller
public function _remap()
{
// Get out URL segments
$segments = $this->uri->uri_string();
$segments = explode("/", $segments);
// Remove blank segments from array
foreach($segments as $key => $value) {
if($value == "" || $value == "NULL") {
unset($segments[$key]);
}
}
// Store our newly filtered array segments
$segments = array_values($segments);
// Works out what segments we have
switch (count($segments))
{
// We have a category/subcategory/page-name
case 3:
list($cat, $subcat, $page_name) = $segments;
break;
// We have a category/page-name
case 2:
list($cat, $page_name) = $segments;
$subcat = NULL;
break;
// We just have a page name, no categories. So /page-name
default:
list($page_name) = $segments;
$cat = $subcat = NULL;
break;
}
if ($cat == '' && $subcat == '') {
$page = $this->mpages->fetch_page('', '', $page_name);
} else if ($cat != '' && $subcat == '') {
$page = $this->mpages->fetch_page($cat, '', $page_name);
} else if ($category != "" && $sub_category != "") {
$page = $this->mpages->fetch_page($cat, $subcat, $page_name);
}
// $page contains your page data, do with it what you wish.
}
?>
You of course would need to modify your page fetching model function accept 3 parameters and then pass in info depending on what page type you are viewing.
In your application/config/routes.php file simply put what specific URL's you would like to route and at the very bottom put this:
/* Admin routes, login routes etc here first */
$route['(:any)'] = "pages"; // Redirect all requests except for ones defined above to the pages controller.
Let me know if you need any more clarification or downloadable example code.

Resources