How to implement Redis in CodeIgniter? - php

I get the tutorial in:
http://yaminnoor.com/redis-codeigniter/
https://codeigniter.com/user_guide/libraries/caching.html#redis
I try it like this:
Config (application\config\redis.php):
defined('BASEPATH') OR exit('No direct script access allowed');
$config['socket_type'] = 'tcp'; //`tcp` or `unix`
$config['socket'] = '/var/run/redis.sock'; // in case of `unix` socket type
$config['host'] = '127.0.0.1'; //change this to match your amazon redis cluster node endpoint
$config['password'] = NULL;
$config['port'] = 6379;
$config['timeout'] = 0;
Controller:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Redis_tes extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->driver('cache', array('adapter' => 'redis', 'backup' => 'file'));
}
public function index() {
// die('tes');
if($this->cache->redis->is_supported() || $this->cache->file->is_supported()) {
$var1 = $this->cache->get('cache_var1');
} else {
$cache_var1 = $this->_model_data->get_var1();
$this->cache->save('cache_var1', $cache_var1);
}
}
}
?>
I run http://localhost/app_redis/redis_tes, which produces the following error:
An Error Was Encountered
Invalid driver requested: CI_Cache_redis
Any solution to solve my problem?

Look here:
https://github.com/joelcox/codeigniter-redis
Try to use this library.
Update : This library is deprecated. Author recommends to migrate on Predis.

Related

PHP Codeigniter - Upload file to Dropbox via HTTPS always empty

I'm trying to upload file using Kunnu Dropbox API. It works really well in localhost. But, when I try to upload from live server, it always upload empty file. What am i missing ?
Here is the code to upload :
$pathToLocalFile = base_url() . "\\public\\dropbox_file\\" . $data['upload_data']['file_name'];
$dropBox = $this->load->library("DropBox_lib");
$drop_obj = new DropBox_lib();
$drop_obj->set_mode_file(1);
$drop_obj->set_drop_file($pathToLocalFile);
$drop_n = $drop_obj->drop_object;
$file = $drop_n->simpleUpload($drop_obj->drop_file, $path_f . "/" . $data['upload_data']['file_name'], ['autorename' => true]);
Here is the Library of Dropbox_lib.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
use Kunnu\Dropbox\Dropbox;
use Kunnu\Dropbox\DropboxApp;
use Kunnu\Dropbox\DropboxFile;
class DropBox_lib{
public $drop_object;
public $drop_file;
public $drop_mode;
public function __construct()
{
require_once APPPATH.'third_party/DropBox/vendor/autoload.php';
//Configure Dropbox Application
$app = new DropboxApp("xxxxxxxxxxxxxxxxx", "yyyyyyyyyyyyyyyyy", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
//Configure Dropbox service
$this->drop_object = new Dropbox($app);
}
public function set_mode_file($mode){
if($mode == 1){
$mode = DropboxFile::MODE_READ;
$this->drop_mode = $mode;
}else{
$mode = DropboxFile::MODE_READ;
$this->drop_mode = $mode;
}
}
public function set_drop_file($pathlocal){
$dropboxFile = new DropboxFile($pathlocal, $this->drop_mode);
$this->drop_file = $dropboxFile;
}
}
?>
The same codes work really well on localhost.

Google Cloud Vision ImageAnnotator Google Application Credential File Not Exist Codeigniter PHP

I have try to implement the google cloud vision with API ImageAnnotator using a codeigniter PHP.
I have install the require google cloud vision using a composer to my third party directory in codeigniter.
This is the code looks like in my controller :
defined('BASEPATH') OR exit('No direct script access allowed');
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
class Manage_center extends CI_Controller {
function __construct() {
parent::__construct();
include APPPATH . 'third_party/vendor/autoload.php';
}
public function index()
{
$this->load->view('index');
}
function upload_ocr_image()
{
//img_data contain image => i just shorten the code.
$img_data = $this->upload->data();
// Authenticating with a keyfile path.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.base_url().'assets/google_cloud_vision/credentials.json');
$scopes = ['https://www.googleapis.com/auth/cloud-vision'];
// create middleware
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
$response = $imageAnnotator->textDetection($img_data['full_path']);
$texts = $response->getTextAnnotations();
printf('%d texts found:' . PHP_EOL, count($texts));
foreach ($texts as $text) {
print($text->getDescription() . PHP_EOL);
# get bounds
$vertices = $text->getBoundingPoly()->getVertices();
$bounds = [];
foreach ($vertices as $vertex) {
$bounds[] = sprintf('(%d,%d)', $vertex->getX(), $vertex->getY());
}
print('Bounds: ' . join(', ',$bounds) . PHP_EOL);
}
$imageAnnotator->close();
}
}
I got the error :
Type: DomainException Message: Unable to read the credential
file specified by GOOGLE_APPLICATION_CREDENTIALS: file
http://localhost/theseeds/assets/google_cloud_vision/credentials.json
does not exist Filename:
D:\xampp\htdocs\theseeds\application\third_party\vendor\google\auth\src\CredentialsLoader.php
Line Number: 74
File:
D:\xampp\htdocs\theseeds\application\controllers\Manage_center.php Line: 3188 Function: getMiddleware
I dont understand why this error occur :
http://localhost/theseeds/assets/google_cloud_vision/credentials.json does not exist
Because when i opened the link the file is there.
And this error :
File:
D:\xampp\htdocs\theseeds\application\controllers\Admin_center.php Line: 3188 Function: getMiddleware
is a line code :
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
What is the proper way to use the google cloud vision ImageAnnotatorClient in codeigniter PHP ?
Is there a problem with the authentication to google cloud api ?
Thank You
I found the solution myself.
This is how the right way to use the google cloud ImageAnnotator with service account key.
defined('BASEPATH') OR exit('No direct script access allowed');
use Google\Cloud\Vision\VisionClient;
class Admin_center extends CI_Controller {
function __construct() {
parent::__construct();
include APPPATH . 'third_party/vendor/autoload.php';
}
public function index() {
$this->load->view('index');
}
function upload_ocr_image() {
$img_data = $this->upload->data();
$vision = new VisionClient(['keyFile' => json_decode(file_get_contents('credentials.json'), true)]);
$imageRes = fopen($img_data['full_path'], 'r');
$image = $vision->image($imageRes,['Text_Detection']);
$result = $vision->annotate($image);
print_r($result);
}
}

Fatal error: Class 'DOMDocument' not found in Codeigniter 2 and PHP 5.1

I use PHP 5.6 in my localhost and this script for generating pdf is working well. But in the server which is using PHP 5.1 I got that error. Here is the script in application/libraries/pdf.php.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once (dirname(__FILE__)) . '/dompdf/dompdf_config.inc.php';
class Pdfgenerator {
function __construct() {
$this->ci =& get_instance();
$this->dompdf = new DOMPDF();
}
function generate($data){
$html = $this->ci->load->view($data['template'],$data,true);
$paper_size = isset($data['paper_size']) ? $data['paper_size'] : 'A4';
$orientation = isset($data['orientation']) ? $data['orientation'] : 'potrait';
$this->dompdf->set_paper($paper_size,$orientation);
$this->dompdf->load_html($html);
$this->dompdf->render();
$this->dompdf->stream($data['filename'].'.pdf',array('Attachment'=>0));
}
}
What should I change to make it works in PHP 5.1?

How can I generate QR Codes from a string in PHP?

I've been playing around trying to generate QR Codes from a string without any luck. I'm using CodeIgniter. I've tried 2 different packages from Packagist, bacon/bacon-qr-code, and endroid/qrcode. Below is the code in my controller for Bacon :
$renderer = new \BaconQrCode\Renderer\Image\Png();
$renderer->setHeight(256);
$renderer->setWidth(256);
$writer = new \BaconQrCode\Writer($renderer);
$writer->writeFile('Hello World!', 'qrcode.png');
When I run this code I get the error 'The phpass class file was not found'.
So I then installed phpass through spark, and I still get the same error. Can anyone tell me what I'm doing wrong?
First one is working as well (probably second one too).
You need to use it this way (at least):
APPPATH . 'libraries/Qrcode.php'
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
use \BaconQrCode\Renderer\Image\Png;
use \BaconQrCode\Writer;
class Qrcode
{
public function test()
{
$renderer = new Png();
$renderer->setHeight(256);
$renderer->setWidth(256);
$writer = new Writer($renderer);
$writer->writeFile('Hello World!', 'qrcode.png');
//var_dump($writer);
}
}
APPPATH . 'controllers/Test.php'
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->qrcode();
}
public function qrcode()
{
$this->load->library('qrcode');
$this->qrcode->test();
}
}
And image will be generated in FCPATH . 'qrcode.png' file.
you can generate QR Codes of string using Google QR Codes API.
https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=Hello+world&choe=UTF-8
300x300 is your image size.
chl - a url encoded string to convert it into qr code.

codeigniter alter Common.php functions

I'm trying to customize the logging functionality of codeigniter. I found this forum thread which describes exactly what I need:
http://codeigniter.com/forums/viewthread/139997/
But I want to do that without altering core files/classes.
I"m trying to alter the log_message function. I've already extended the CI_Log class and that is working well, but now I'm trying to alter log_message() which resides in system/core/Common.php. It isn't actually a class so I can't extend it, it just appears to be a collection of useful functions. I tried redeclaring log_message() and placing it in application/core/Common.php, but that doesn't appear to work. Any ideas how I can go about this?
I believe that the function you actually want to alter is write_log(), correct me if I'm wrong. You can do this by extending the function within application\libraries\MY_Log.php.
I have the following script in my MY_Log.php which emails me any time an error is thrown:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Extends the logging class to send an email when an error is triggered */
class MY_Log extends CI_Log {
function __construct()
{
parent::__construct();
}
function write_log($level = 'error', $msg, $php_error = FALSE, $additional, $additional2)
{
if ($this->_enabled === FALSE)
{
return FALSE;
}
$level = strtoupper($level);
if ( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
{
return FALSE;
}
$filepath = $this->_log_path.'log-'.date('Y-m-d').'.php';
$message = '';
if ( ! file_exists($filepath))
{
$message .= "<"."?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n";
}
if ( ! $fp = #fopen($filepath, FOPEN_WRITE_CREATE))
{
return FALSE;
}
$message .= $level.' '.(($level == 'INFO') ? ' -' : '-').' '.date($this->_date_fmt). ' --> '.$msg."\n";
flock($fp, LOCK_EX);
fwrite($fp, $message);
flock($fp, LOCK_UN);
fclose($fp);
#chmod($filepath, FILE_WRITE_MODE);
return TRUE;
}
}
If you're not looking to extend the write function, you will need to extend one of the other log functions.
A helper function could work here. You'd have to use it instead of log_message().
Here's what I did:
in application/helpers I created 'new_log_helper.php' (helpers have to end in _helper.php)
I wanted this to add log entries into the database and to track by process (that way I know where to look in the code).
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Custom Logging Interface
*
* Add log entries to a log table on the db and track process name
*
* #access public
* #return void
*/
if ( ! function_exists('new_log')) {
function new_log($level = 'error', $message, $process, $php_error = FALSE)
{
if (config_item('log_threshold') == 0) {
return;
}
$CI =& get_instance();
$CI->load->model('new_log','logger', TRUE);
$CI->logger->add_event($process, $level, $message);
log_message($level, $process.': '.$message, $php_error);
}
}
Then when you need it use it like this:
$this->load->helper('new_log');
...
new_log('debug','Something happened','Stack overflow answer');
Anyway I know your issue was years ago but I was looking so maybe someone else is too.

Categories