Clear cache on CodeIgniter using wildcard - codeigniter

CodeIgniter documentation specified only two-ways to delete cache. They are:
$this->cache->delete('cache_item_id')
- for deleting individual cache thru ID
$this->cache->clean()
- for deleting ALL cache
My website have static and dynamic content and I would like to delete all the cache on the latter only.
I'm looking for something like ->delete("latest*") that will delete "latest-video", "latest-video-funny", "latest-video-music", "latest-article", etc.

I think I've got it working, calling $this->cache->cache_info(); will fetch a multidimensional array of all saved cache. The array keys inside the fetch array are the cache_item_id so I can just do the following.
$wildcard = 'latest';
$all_cache = $this->cache->cache_info();
foreach ($all_cache as $cache_id => $cache) :
if (strpos($cache_id, $wildcard) !== false) :
$this->cache->delete($cache_id);
endif;
endforeach;

There is a helper that does this, you can find it here.
how is cache created
$path = $CI->config->item('cache_path');
$cache_path = ($path == '') ? APPPATH.'cache/' : $path;
.
.
.
$uri = $CI->config->item('base_url').
$CI->config->item('index_page').
$CI->uri->uri_string();
$cache_path .= md5($uri);
helper itself
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('delete_cache'))
{
function delete_cache($uri_string)
{
$CI =& get_instance();
$path = $CI->config->item('cache_path');
$cache_path = ($path == '') ? APPPATH.'cache/' : $path;
$uri = $CI->config->item('base_url').
$CI->config->item('index_page').
$uri_string;
$cache_path .= md5($uri);
if (file_exists($cache_path))
{
return unlink($cache_path);
}
else
{
return TRUE;
}
}
}
all credits go to Steven Benner, his blog.
usage:
delete_cache('/blog/comments/123');

Related

Change download filename codeigniter

Convert file name before force download.
I am trying to be able to convert the file name of the stored file name to the orignal file name before download
So when user clicks on a file to download instead of showing
post_1486965530_jeJNHKWXPMrwRpGBYxczIfTbaqhLnDVO.php
Like in image below
It will just rename the downloaded file something like
config.php
Question how to only change the downloaded filename when click on image.
public function downloads($id) {
$this->db->where('attachment_id', $id);
$query = $this->db->get('attachments');
if ($query->num_rows() == 0) {
return false;
}
$path = '';
$file = '';
foreach ($query->result_array() as $result) {
$path .= FCPATH . 'uploads/';
// This gives the stored file name
// This is folder 201702
// Looks like 201702/post_1486965530_jeJNHKWXPMrwRpGBYxczIfTbaqhLnDVO.php
$stored_file_name .= $result['attachment_name'];
// Out puts just example "config.php"
$original .= $result['file_name'];
}
force_download($path . $stored_file_name, NULL);
}
How about that
(imho your foreach loop doesn't make any sense)
public function downloads($id) {
$this->db->where('attachment_id', $id);
$query = $this->db->get('attachments');
if ($query->num_rows() == 0) {
return false;
}
$path = '';
$file = '';
foreach ($query->result_array() as $result) {
$path .= FCPATH . 'uploads/';
// This gives the stored file name
// This is folder 201702
// Looks like 201702/post_1486965530_jeJNHKWXPMrwRpGBYxczIfTbaqhLnDVO.php
$stored_file_name .= $result['attachment_name'];
// Out puts just example "config.php"
$original .= $result['file_name'];
}
force_download("your_filename.txt",file_get_contents($path . $stored_file_name));
}
Simple like that!
force_download(
$filenameWithFileExtension,
file_get_contents($fileToDownload),
mime_content_type($fileToDownload)
);
For this situation use force_download() something like this -
$file_name = "using md5 to convert it on normal text and stroe variable";
$file_path = "It's your file path, where have file in your drive"
$file_path = 'uploads/'.$path;
force_download($file_name, file_get_contents($file_path));
It's simple and working fine. Just need to store your file path and file name store in 2 different variables and pass them in force_download().
Hope it's work.
Good Luck.

Magento sort media folder files by filename

I want to sort media folder files by filename.I tried with
$collection = $this->getCollection($path)
->setCollectDirs(false)
->setCollectFiles(true)
->setCollectRecursively(false)
->setOrder('filename', Varien_Data_Collection::SORT_ORDER_ASC);
but it is not case sensitive.It sorts all upper case words first then lowercase. (Apple,Bat,apple)
Please help !!!
You have to rewrite lib/Varien/Data/Collection/Filesystem.php
and change function
protected function _usort($a, $b)
{
foreach ($this->_orders as $key => $direction) {
$result = $a[$key] > $b[$key] ? 1 : ($a[$key] < $b[$key] ? -1 : 0);
return (self::SORT_ORDER_ASC === strtoupper($direction) ? $result : -$result);
break;
}
}
Please try this:
- create a test.php file in magento root directory.
- change the name of media folder to $sub_dir variable.
<?php
require_once 'app/Mage.php';
Mage::app();
$file = new Varien_Io_File();
$sub_dir = "wysiwyg/new";
$dir = Mage::getBaseDir('media') . DS . $sub_dir . DS;
$file->open(array('path' => $dir));
$fileDetails = $file->ls();
$allFiles = array();
foreach ($fileDetails as $value) {
$allFiles[] = $value['text'];
}
echo "<pre>";
print_r($allFiles);
echo "</pre>";
?>

Anchor Text - Can you hide it? (URL Helper)

Is there anyway to hide the anchor text of the generated by CI? I know I could hide this via CSS (i.e. negative text-indent), but that seems like a lot of unnecessary work. Why wouldn’t I just use a regular HTML coded anchor?
<?php echo anchor(base_url(),''); ?>
Perhaps they thought that people would likely be passing in a blank string more by mistake than by design, I don't know and can't answer that part of your question.
Using the CodeIgniter anchor method in the URL helper has the advantage of automatically adding in your website's base path if necessary.
If you want to keep using the CodeIgniter helper and have anchors with no anchor text, you have several options:
Option 1: Add a space in the second argument:
<?php echo anchor(base_url(),' '); ?>
Option 2: Extend the URL helper and remove the behaviour:
Go into application\helpers and make a new file, called MY_url_helper.php
You can then put code in there to either replace the anchor method or define an entirely new method.
Here are some code examples of what you could put in the file: (I've adapted the code from the url_helper in a CodeIgniter installation I had handy)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('anchor_hide_text'))
{
function anchor_hide_text($uri = '', $title = '', $attributes = '')
{
$title = (string) $title;
if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>';
}
}
or
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function anchor($uri = '', $title = '', $attributes = '')
{
$title = (string) $title;
if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>';
}

How to access Magento from CodeIgniter?

I have a default CodeIgniter 2.1 install with Magento 10.4.4 installed in a subdir called store.
The following code works when run from web root (with .htaccess disabled). It will give the firstname, lastname of the logged in Magento user.
<?php
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
?>
But, if I run this in a CodeIgniter model, then isLoggedIn returns false.
Here is the CodeIgniter page:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
}
}
CodeIgniter is doing something that I have not been able to track yet. The websiteId is returned correctly, but isLoggedIn returns false.
Anyone have any ideas? THANKS!!
I use both but ive never tried to mash them like that. I foresee quite a few problems.
How are you patching into magento?
You might need two db connections running :
$db['magento']
$db['default'] // codeigniter default
Sessions could become a real problem here also aswell as config data.
Consider sticking with magento for now, then maybe patch into your blog/website via a RESTFul service.
Both code examples above work fine. The problem I had was calling session_start() near the top of the CodeIgniter index.php file. Once that was removed, it all started working.
For posterity, here is a Magento 10 Library for CodeIgniter 2.1:
application/libraries/magento.php
<?php if ( ! defined('BASEPATH')) exit("No direct script access allowed");
Class Magento {
function __construct($params)
{
global $site_root;
$name = $params['name'];
// Include Magento application
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
// Uncomment next line if you have moved app/etc
// $options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options=null);
return Mage::getSingleton("core/session", array("name" => $name));
}
}
// end of magento.php
Usage example app/model/test_mage.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
$params = array('name' => 'frontend'); // frontend or adminhtml
$this->load->library('magento', $params);
}
public function index()
{
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if ($session->isLoggedIn())
{
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}
else
$magento_message .= 'Guest!';
echo $magento_message . '<br>';
}
}
// end of test_mage.php

Can't use session variable in routes.php file in codeigniter?

I am use following code to retrieve the session variable in routes.php
if($this->db_session->userdata('request_url')!="")
{
$route['user/(:any)'] = "search_user_name/redirect_url/".$_SESSION['request_url'];
$this->db_session->unset_userdata('request_url');
}
else {
$route['user/(:any)'] = "search_user_name/index/$1";
}
the session variable would be set into template/header.php
$this->db_session->set_userdata('request_url', $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
You can not use db_session in routes.php because routes.php is parsed before db_session is loaded.
Maybe you should create a base controller and redirect from the constructor of the base controller.
Correct me if iam wrong.
You can use hooks.
Codeigniter user guide hooks
You can use database in routes and put your routes url in database.
Here is an example:
require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$table2 = $db->dbprefix.'lang';
$query2 = $db->get( $table2 );
$result2 = $query2->result();
foreach( $result2 as $row )
{
$fields = $db->list_fields($table2);
$findme = 'code';
foreach($fields as $field):
$pos = strpos($field, $findme);
if($pos !== false and $row->$field != ''):
$route[''.$row->$field.''] = 'main/setlang/$1';
endif;
endforeach;
}

Resources