I created a helper for visit hits and it contains a function which inserts some data in to the database:
hits_counter_helper.php :
function count_hits($options = array())
{
//Determine whether the user agent browsing your site is a web browser, a mobile device, or a robot.
if ($this->agent->is_browser())
{
$agent = $this->agent->browser() . ' ' . $this->agent->version() . ' - ' . $this->agent->platform();
}
elseif ($this->agent->is_robot())
{
$agent = $this->agent->robot();
}
elseif ($this->agent->is_mobile())
{
$agent = $this->agent->mobile();
}
else
{
$agent = 'Unidentified User Agent';
}
//Detect if the user is referred from another page
if ($this->agent->is_referral())
{
$referrer = $this->agent->referrer();
}
// correcting date time difference by adding 563 to it.
$date = date('Y-m-j H:i:s', strtotime(date('Y-m-j H:i:s')) + 563);
$data = array (
'page_Address' => current_url(),
'user_IP' => $this->input->ip_address(),
'user_Agent' => $agent,
'user_Referrer' => $referrer,
'hit_Date' => $date
);
$this->db->insert('counter', $data);
}
once I auto loaded the helper and called this function in my controller as:
My_controller.php:
public function index() {
count_hits();
//index code here
}
The problem is that I am getting a blank page and other codes does not run I think. What am I doing wrong?!
Add the following code to the beginning of your helper function:
//get main CodeIgniter object
$CI =& get_instance();
Replace all $this with $CI in your function.
and then load the helper function wherever you want in your controller like this:
count_hits();
Related
I try to post an article to Bexio via the Bexio API: https://docs.bexio.com/resources/article/
There is also a sample for PHP: https://docs.bexio.com/samples/
I updated the scopes in the config.php to allow read and write articles.
I updates the bexioConnector.class.php so i can get Articles (works):
public function getArticles($urlParams = array()) {
return $this->call('article', $urlParams);
}
public function call($ressource, $urlParams = array(), $postParams = array(), $method = Curl::METHOD_GET) {
$url = $this->api_url . "/" . $this->org . "/" . $ressource;
$data = $this->curl->call($url, $urlParams, $postParams, $method, $this->getDefaultHeaders());
return json_decode($data, true);
}
So i can use now this code to get all articles (works):
$bexioProducts = $con->getArticles(array('order_by' => 'id'));
Now i want to create articles with the POST method.
So i added this function to the bexioConnector.class.php
public function postArticle($postParams = array(), $urlParams = array()) {
return $this->call('article', $urlParams, $postParams, Curl::METHOD_POST);
}
So i use this code to create a product:
$con->postArticle(array(
'intern_code' => "SKU-3214"
)
);
But this ends in an error:
{"error_code":415,"message":"Could not parse the data."}
I have tried a lot but i always get the same error message.
What could i have don possibly wrong?
I found the error. I need to encode it as a json first.
So i changed my postArticle function:
public function postArticle($postParams = array(), $urlParams = array()) {
$json = json_encode($postParams);
return $this->call('article', $urlParams, $json, Curl::METHOD_POST);
}
Here is my code:
public function save_problem(Request $request)
{
$doesnot_turn_on = isset($request->doesnot_turn_on) ? $request->doesnot_turn_on : "";
$res = setcookie('guarantee_ticket', json_encode(["title"=>$request->problem_title, "description"=>$request->problem_description, "turn_on" => $doesnot_turn_on, "unique_product_id" => $request->unique_product_id]), time() + 200000, "/");
if ( Auth::check() ){
return $this->register_guarantee_ticket();
} else {
return \redirect()->route('short_register',["des" => route('register_guarantee_ticket')]);
}
}
public function register_guarantee_ticket()
{
$problem = json_decode($_COOKIE['guarantee_ticket']);
.
.
As you can see, when Auth::check() is true, then register_guarantee_ticket() will be called while still $_COOKIE['guarantee_ticket'] isn't defined and it (cookie) needs a page reloading to be defined.
How can I make that page reloading with PHP?
I know header("Location: ...") will be used for redirecting. But how can I keep the process and do also a redirect?
The problem is why you need reloading the page while the request is processing (that's impossible in HTTP mechanism)
So I have an idea for you to fix this (by passing cookie data to sub-function) :
public function save_problem(Request $request)
{
$doesnot_turn_on = isset($request->doesnot_turn_on) ? $request->doesnot_turn_on : "";
$cookie_data = ["title"=>$request->problem_title, "description"=>$request->problem_description, "turn_on" => $doesnot_turn_on, "unique_product_id" => $request->unique_product_id];
$res = setcookie('guarantee_ticket', json_encode($cookie_data), time() + 200000, "/");
if ( Auth::check() ){
return $this->register_guarantee_ticket();
} else {
return \redirect()->route('short_register',["des" => route('register_guarantee_ticket')]);
}
}
public function register_guarantee_ticket($cookie_data)
{
$problem = $cookie_data; // No need this assign, but I put it here to point out you should pass cookie data directly to sub-function
.
.
I need to create a query log in my project. So I created a post_controller hook. It saves all the executed queries in both a text file and a database. But it works only for SELECT queries. I know it is repeated question, but after a lot of search, I couldn't find solution.
Here is my code:
config/hooks.php:
$hook['post_controller'] = array(
'class' => 'LogQueryHook',
'function' => 'log_queries',
'filename' => 'log_queries.php',
'filepath' => 'hooks'
);
hooks/log_queries.php
class LogQueryHook {
function log_queries() {
$CI =& get_instance();
$times = $CI->db->query_times;
//$dbs = array();
$output = NULL;
$queries = $CI->db->queries;
//print_r($queries);
if (count($queries) == 0){
$output .= "no queries\n";
}else{
foreach ($queries as $key=>$query){
$took = round(doubleval($times[$key]), 3);
$CI->db->query('INSERT INTO queryLog_tbl(`query`, `executedTime`, `timeTaken`, `executedBy`) VALUES ("'.$query.'", "'.date('Y-m-d h:i:s').'", "'.$took.'","'.$CI->session->userdata('UserID').'")');
$output .= $query . "\n";
$output .= "===[took:{$took}]\n\n";
}
}
$CI->load->helper('file');
if ( ! write_file(APPPATH . "/logs/queries.log.txt", $output, 'a+')){
log_message('debug','Unable to write query the file');
}
}
}
and hooks enabled in my config.php : $config['enable_hooks'] = TRUE;
You need to check your internal redirection after any modification query(Insert, Update or delete query) executed. If you put any redirect statement after modification query then it will overtake hook execution.
You can do it by overwriting the query() method in system/database/DB_driver.php
Or
Create library and call it from relevant controllers.
My code skipping all queries other than SELECT because of internal redirection. So I created a library for this. I am attaching my code here. It may help someone else
application/libraries/Querylog.php
class Querylog {
protected $CI;
public function __construct() {
$this->CI =& get_instance();
}
function save_query_in_db() {
$query = $this->CI->db->last_query();
$times = $this->CI->db->query_times;
$time = round(doubleval($times[2]), 5);
$this->CI->db->query('INSERT INTO queryLog_tbl(`query`, `executedTime`, `timeTaken`, `executedBy`) '
. 'VALUES ("'.$query.'", "'.date('Y-m-d h:i:s').'", "'.$time.'","'.$this->CI->session->userdata('UserID').'")');
}
}
load this library in your controller or autoload.php
and call save_query_in_db() where ever you want
eg: in model :
$this->db->set('status', 1);
$this->db->where('UserID', $this->session->userdata('UserID'));
$this->db->update('user_tbl');
$this->querylog->save_query_in_db();
I am trying to record the page details which the user is visiting and store them in the database. So, I wrote a function in a helper named hits_helper.php which uses the current_url() of codeigniter to do it.
function count_hits($options = array())
{
$CI =& get_instance();
$CI->load->library('user_agent');
$date = date('Y-m-j H:i:s', strtotime(date('Y-m-j H:i:s')) + 1214);
$data = array (
'page_Address' => current_url(),
'hit_Date' => $date
);
$CI->db->insert('counter', $data);
}
url helper is autoloaded.
It works and inserts the page url in the database, but it also inserts some urls like the favicon.ico and some css urls in the head section of the page respectively. What am I doing wrong?!
Create new helper name My_url_helper
function current_url()
{
$CI =& get_instance();
$url = $CI->config->site_url($CI->uri->uri_string());
return $_SERVER['QUERY_STRING'] ? $url.'?'.$_SERVER['QUERY_STRING'] : $url;
}
May be it help you
You're not doing anything wrong, and your model function does what it is suppose to do. Using this approach, you could create a filter function, to exclude exceptions, like this:
function filter_hits(){
$exeptions = array('css', 'js', 'images');
foreach($exceptions as $exception){
if(!strpos(current_url(), 'http://'. base_url() . $exception))
$this->count_hits(current_url());
}
}
, where count_hits() would take current_url() string as parameter.
function count_hits($current_url, $options = array())
{
$CI =& get_instance();
$CI->load->library('user_agent');
$date = date('Y-m-j H:i:s', strtotime(date('Y-m-j H:i:s')) + 1214);
$data = array (
'page_Address' => $current_url,
'hit_Date' => $date
);
$CI->db->insert('counter', $data);
}
I'm having a very strange and weird issue in Facebook connect API inside my Codeigniter 2.1 project. My site has social login feature and all the codes I test in my localhost works perfectly well. But When I upload my project to the hosting server, Facebook connect library returns null object all the times.
I'm using facebook-php-sdk 3.2 and bellow here is the code I that I'm using.
in the config folder I've a file named, facebook.php that contains
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
$config = array(
'appId' => 'xxxxxxxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
);
?>
I've a library named Fbconnect.php under my library folder. Contains code
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
include (APPPATH . 'libraries/facebook/facebook.php');
class Fbconnect extends Facebook {
/**
* Configured the facebook object
*/enter code here
public $user = null;
public $user_id = null;
public $fb = false;
public $fbSession = false;
public $appkey = 0;
public function __construct() {
$ci = & get_instance();
$ci->config->load('facebook', true);
$config = $ci->config->item('facebook');
parent::__construct($config);
$this->user_id = $this->getUser();
$me = null;
if ($this->user_id) {
try {
$me = $this->api('/me');
$this->user = $me;
} catch (FacebookApiException $e) {
error_log($e);
}
}
}
}
?>
and below here is my controller's code
public function fb_login()
{
$this->load->library('fbconnect');
$user_data = array(
'redirect_uri' => actionLink("signup", 'social', 'Facebook'),
'scope' => 'email'
);
redirect($this->fbconnect->getLoginUrl($user_data));
}
I've created a helper function named actionLink, here is it's code
function actionLink($controller = '', $action = '', $param = '')
{
$url = base_url();
if (strlen($controller) > 0) {
$url .= "$controller";
if (strlen($action) > 0) {
$url .= "/$action";
if (strlen($param) > 0) {
$url .= "/$param";
}
}
}
return $url;
}
Please Help.
In Signup.php replace line nos. 37 to 46 with the following: //inside function social($userType = 'Web')
1. Try Solution No.1 Just to make sure that its working but its not genral, It's specific to Facebook.
2. Solution No.2 is same as what you have done but in CI's Way :)
Solution No. 1:
$this->load->library('fbconnect');
$socialId = $this->fbconnect->getSocialId();
$this->data['social_id'] = $socialId;
$email = $this->fbconnect->getEmail();
$this->data['email'] = $email;
$name = $this->fbconnect->getName();
$this->data['name'] = $name;
$this->data['url'] = $userType;
Solution No. 2:
$className = $userType . "SocialService";
$this->load->library($className);
$socialId = $this->$className->getSocialId();
$this->data['social_id'] = $socialId;
$email = $this->$className->getEmail();
$this->data['email'] = $email;
$name = $this->$className->getName();
$this->data['name'] = $name;
$this->data['url'] = $userType;
Actually Your main problem is in FacebookSocialService.php. You are trying to call a private method within a public method in an incorrect way. That's the reason you are not able to fetch any details. Solution for that is as follows:
Inside your public methods
public function getSomeData()
{
$fbSocialService = new FacebookSocialService();
$some_fb_data = $fbSocialService->getFacebook()->user['some_fb_data'];
return $some_fb_data;
}
But rather than doing this, You can just make the private method as public. ;) (Just kidding, but its very quick fix) :P