How can I generate QR Codes from a string in PHP? - 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.

Related

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 to implement Redis in CodeIgniter?

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.

Including a file in CodeIgniter model is causing the server to dump the script on the web page

I'm trying to develop an application on code igniter framework. My question is when I wrote the model of my application it grew large, so I broke it down into two separate file. The main files merely calls the other one using include command.
The problem is that the calling file dumps the script in the called file in plain text on the web browser.
my model file looks like this :
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Admin_model extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
public function return_admin_dashboard_articles($priviledge_id,$by_author=null,$date_published=null){
$index = 0;
$query_articles = null;
//fetching list of articles
include 'includes/posts_query.inc.php';
return $data;
}
}
?>
and the file posts_query.inc.php looks like this:
<?php>
if($priviledge_id==1 || $priviledge_id==2){
$this->db->select('articles.id,articles.title,articles.summary,users.user_name,date(articles.pub_date) as
pubs_date,articles.author');//add date and time stamp to the table
$this->db->from('articles');
$this->db->join('users','articles.author=users.user_id');
if($by_author and $date_published==null){
$this->db->where('articles.author',$by_author);
}
else if($by_author=='all' and $date_published){
$this->db->where('date(articles.pub_date)=',$date_published);
}
$this->db->where('users.user_priviledge_id=',$priviledge_id); //change this to user_priviledge_id>$priviledge_id to see articles by all the users
$query_articles = $this->db->get();
}
//echo $query_articles;
else{
$this->db->select('articles.id,articles.title,articles.summary,users.user_name,date(articles.pub_date) as pubs_date,articles.author');//add date and time stamp to the table:done
$this->db->from('articles');
$this->db->join('users','articles.author=users.user_id');
$this->db->where('users.user_priviledge_id=',$priviledge_id);
$query_articles = $this->db->get();
}
if($query_articles->num_rows()>0){
foreach($query_articles->result_array() as $row){
$data['articles'][$index]=array(
'id'=>$row['id'],
'title'=>$row['title'],
'summary'=>$row['summary'],
'author'=>$row['user_name'],
'date'=>$row['pubs_date'],
'author_id'=>$row['author']
//'time'=>$row['time']
);
$index++;
}
}
else{
$data['error']['articles']='Could not fetch articles';
}
?>
The complete posts_query.inc.php file is displayed on the web page. What is the reason behind this? Any help will be much appreciated.
Thanks.
I'm running XAMPP (Apache 2.4.10, PHP 5.6.3,MySql 5.6 CodeIgniter 3.0) on windows 10.
The posts_query.inc.php file begins with <?php>.
It should be <?php. The > is causing the problem.

Best way for scripts in codeigniter

In CodeIgniter I often have many scripts inherent to my project, for instance:
<?php
// Load many things
$this->load->model('news_model');
$this->load->helper('utility_helper');
$news = $this->news_model->get_basic_news();
// For moment no news
$view_datas['news']['check'] = false;
if ($news) {
$view_datas['news'] = array(
'check' => true,
'news' => _humanize_news($news)
);
}
?>
This script is used in different controllers, at the moment I create a scripts folder and I import it like that: include(APPPATH . 'scripts/last_news.php'); I'm quite sure it's not the best way to handle this problem. Any thoughts on that?
Update:
A solution given in the answers is to use a helper or a library.
Let's imagine a rewrite of my previous code:
class Scripts {
public function last_news() {
// Load many things to use
$CI =& get_instance();
$CI->load->model('news_model');
$CI->load->model('utility_helper');
$news = $CI->news_model->get_basic_news();
// Avoid the rest of code
}
}
Just create a new library and load that library whereever you require?
e.g.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Newclass {
public function get_news($limit)
{
//return news
}
}
/* End of file Newsclass.php */
In your controllers
$this->load->library('newsclass');
$this->newsclass->get_news($limit);
Or another idea is to create helper functions.

Categories