I'm looking for a way to catch all the database errors (if and when they occur) and sent an error report my email. For regular php error I extended the CI_Exceptions class and added my email sending code in addition to logging. But the database errors don't go trough CI_Exceptions but instead are logged directly from CI_DB_Driver->query() and I don't want to modify any file in the System folder.
Also I don't want to write logging code around every query the app does.
I'd be tempted to extend CI_Exceptions show_error method to catch any errors passed with the 'error_db' template rather than hunting through the db driver.
As you've already extended CI_Exceptions with email code this would seem like the best practice.
function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
set_status_header($status_code);
$message = '<p>'.implode('</p><p>', ( ! is_array($message)) ? array($message) : $message).'</p>';
if ($template == 'error_db')
{
// do email send here with $message
}
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include(APPPATH.'errors/'.$template.'.php');
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
Related
set_flashdata is not working directly after redirect with only one redirect.
I am using one controller in this process - Profilers' Controller. It handles the member confirmation process and also displays the login page on the redirect. The process is as follows:
this session set_flashdata ('topic', 'newmember')
redirect ('login')
route ['login'] = 'profilers/signIn'
topic = $this session flashdata ('topic')
I have turned off all database session configuration for cleaner debugging and even though session library is turned on in configs, I have started calling it anyways which doesn't seem to work either.
Here is my code. As you can see, I am sending path info to a log file path.log:
in controller Profilers, function confirmMember:
public function confirmMember()
{
//use_ssl();
$this->form_validation->set_rules('handle', 'Unique Member Name', 'trim|xss_clean|required|min_length[5]|max_length[30]');
$this->form_validation->set_rules('confirmation', 'Confirmation Code', 'trim|xss_clean|required|min_length[20]|max_length[20]|alpha_numeric');
if ($this->form_validation->run() === FALSE) {echo "here";exit;
$data['handle']=$this->input->post('handle');
$data['confirmation']=$this->input->post('confirmation');
$this->load->view('signing/defaults/header',$data);
$this->load->view('defaults/heading',$data);
$this->load->view('defaults/banner');
$this->load->view('defaults/banner_right');
$this->load->view('member/temp/index',$data);
$this->load->view('defaults/footer',$data);
} else {
$post = $this->input->post(NULL,TRUE);
$data['member'] = $this->Signing_model->model_confirmMember($post);
if ($data['member']['confirmed']!==FALSE) {
/* PATH CHECK */
error_log("member confirmation not false\n",3, LOG_DIR.'path.log');
unset($post);
$this->session->sess_destroy();
$this->session->set_flashdata('topic', 'newmember');
// $this->session->keep_flashdata('topic');
redirect('login','refresh');
} else {
/* PATH CHECK */
error_log("member confirmation IS FALSE\n",3, LOG_DIR.'path.log');
$this->load->view('member/temp/index',$data);
}
My log file shows that the path is using the correct path and showing "member confirmation not false".
I have tried with keep_flash data on (which I assumed wouldn't work since there are no other redirects) and off.
I have also tried redirect without 'refresh'.
In config/routes.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$route['join'] = 'profilers/joinUp';
$route['login'] = 'profilers/signIn';
...
Login page uses Profilers Controller, signIn function as show above:
public function signIn()
{
$topic = $this->session->flashdata('topic');
if (isset($topic)) {
$message = "topic is set. topic = ".$topic."\n";
if ($topic!==FALSE) {
error_log("flash var topic is not false\n", 3, LOG_DIR.'path.log');
} else {
error_log("flash var topic is FALSE\n", 3, LOG_DIR.'path.log');
}
} else {
$message = "topic is NOT set\n";
}
error_log($message,3,LOG_DIR.'path.log');
exit;
...
...
}
log file is showing that topic is set but is false.
"flash var topic is FALSE"
"topic is set. topic = "
Of course topic var not set since it is FALSE.
As you can see, I have moved the get flash data function to the beginning of my controller function to bypass anything that may be corrupting data.
You may need to start the session again after you have destroyed it.
Try adding this after your call to sess_destory():
$this->session->sess_create()
Alternatively you could avoid destroying the session, and unset() the values you wish to get rid of.
I have set up my routes.php to suit the nature of my site. Unfortunately, there is a problem with my last route i.e.:
$route['(:any)'] = "profile/profile_guest/$1";
If the username password name passed is correct, for e.g. domain.com/username, it will load his/her data. if not, it loads the page with errors (because failure to retrieve data with non-existent user in database). This is my problem! I want to avoid this error showing.
Is there anyway I could avoid this error from happening? None of the echoes seems to be printing or the redirect neither is working. Don't know why! it is as if the code inside this method is not executing and the view is loaded instead. below is part of the profile_guest function:
public function profile_guest($username)
{
$username = $this->uri->segment(1);
//echo "Hello " . $username;
redirect('main', 'refresh');
if($username != '')
{
/* echo "<h1>HELLO WORLD SOMETHING</h1>"; */
It's hard to say without seeing the rest of the code.
Maybe you need to check the value before running the query:
// user_model
function get_user($username = NULL){
if($username){
return $this->db->query(...
}else{
return false;
}
}
Then check that the query returned anything before loading the view
if($this->user_model->get_user($username){
//show the page
}else{
echo "no user found";
}
When I am trying to set the custom message for an error under from_validation library in CodeIgniter using the following statement..
$this->form_validation->set_message("is_unique", "%s already registered. Try a different %s");
Instead of getting Username already registered. Try a different Username I'm getting Username already registered. Try a different users.username
While the documentation says If you include %s in your error string, it will be replaced with the "human" name you used for your field when you set your rules.
Please get me out of the trap.
Looking at your problem it seems that the language file you are using does not have an index user.username. Define it in the user language file and see what happens.
Here is the Reference to language
Codeigniter Language Class
And
Codeigntier Language Helper
I faced same problem , while i am searching i found this answer which mentioned the line in Codeigniter that builds the error message (located in file system/libraries/form_validation.php) near line 673:
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
I edited it to :
// Build the error message
if($rule == 'is_unique') { //my code here
$vars_num = substr_count($line, '%s'); //my code here
for($i = 0; $i < $vars_num; $i++){ //my code here
$params[] = $this->_translate_fieldname($row['label']); //my code here
} //my code here
$message = vsprintf($line, $params); //my code here
} else { //my code here
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
}
and it works fine for me .
i know it is not best practice to edit system libraries but maybe it will help you.
Try this:
$this->form_validation->set_message("is_unique", "{field} already registered. Try a different {field}");
You can set Custom Message with Message library of codigniter
For Example
in Model Coding Like this
if(duplicate_user_name ==true){
$this->messages->add('$user already registered. Try a different $user ', 'error');
}
and Print this message with following View
$messages = $this->messages->get();
if (is_array($messages)):
foreach ($messages as $type => $msgs):
if (count($msgs > 0)):
foreach ($msgs as $message):
echo ('<div class="' . $type .'">' . $message . '</div>');
endforeach;
endif;
endforeach;
endif;
I'm running into a problem I just can't seem to fix. I'm working on kind of a CMS kind of thing. And one of the functions is making image slideshows.
In one controller, I check if a slideshow with a certain ID exists, and if it exists, it should take the data and work with it, otherwise, set an error message (CodeIgniter flashdata) and redirect to the homepage.
The code I use for this is the following:
if($this->Mslideshow->slideshowExists($showid) === FALSE){
echo 'I\'m getting here';
$this->session->set_flashdata('error',$showid);
redirect('admin/index','refresh');
}else{
echo 'Slideshow exists';
}
And the code of the slideshowExists() function is:
public function slideshowExists($showid)
{
$this->db->where('id',$showid)
->limit(1);
$query = $this->db->get('slideshows');
if($query->num_rows() < 1){
return FALSE;
}
$this->currentquery = $query;
return TRUE;
}
And the problem is this, very strange actually. If the result I get back is FALSE, everything goes as planned. Error message gets set and redirect goes to 'admin/index'.
But if what I get back is TRUE, then the stange thing happens. I do get an echo with 'Slideshow exists', but I also get the error message.
I've tried everything, deleted cookies. Reset all sessions etc.
And even stranger is that when I tried to put the $showid I use to check into the error message, all of a sudden $showid is ' img '. While everywhere else is '1' or '2'...
Hope someone can help. Thanks!
=====EDIT=====
I tried to edit the code and simplify it. Right now I have this code in my Controller:
public function slideshow($showid){
$query = $this->db->where('id',$showid)->get('slideshows');
if($query->num_rows() < 1){
$this->session->set_flashdata('error','Slideshow doesn\'t exist.');
redirect('admin/index','refresh');
}
$data['page'] = 'slideshow';
$data['title'] = 'Slideshows';
$this->scripts->load_scripts(array());
$this->scripts->load_functions(array());
$this->load->view('admin/dashboard_template.php',$data);
}
When I run this with a $showid, that doesn't exist, I get the error message after being redirected to 'admin/index'. When I use a $showid that does exist, I do get the error, but no redirect but just the rest of the code.
I think you have to read your flash data in your view:
$error = $this->session->flashdata('error');
var_dump($error);
or in your Controller:
$error = $this->session->flashdata('error');
if(isset($error)) {
var_dump($error);
}
Also you can read this question: CodeIgniter "flashdata" doesn't work
you can get the flash data by following way
$error = $this->session->flashdata('error');
if($error)
{
echo $error;
}
You can try
if($this->session->flashdata('msg') != "")
This works for me.
For example in my logs I have many lines that repeat, such as:
ERROR - 2011-07-06 09:19:01 --> 404 Page Not Found --> favicon.ico
Is there any way for me to find out who is calling these errant URLs? The favicon is just an example, there are some URLs that for example show an intent to hack, and others it's just the same error repeated over and over and over again. Basically I'd love to know which IP's to potentially block as well as what sites to contact if they have bad links (or if I should just redirect them on my server with .htaccess).
If you feel the need to do this, just extend the Exceptions class and override the show_404() function:
// v2.x: core/MY_Exceptions.php
// v1.x: libraries/MY_Exceptions.php
class MY_Exceptions extends CI_Exceptions {
/**
* 404 Page Not Found Handler
*
* #access private
* #param string
* #return string
*/
function show_404($page = '', $log_error = TRUE)
{
$heading = "404 Page Not Found";
$message = "The page you requested was not found.";
// By default we log this, but allow a dev to skip it
if ($log_error)
{
// Custom code here, maybe logging some $_SERVER variables
// $_SERVER['HTTP_REFERER'] or $_SERVER['REMOTE_ADDR'] perhaps
// Just add whatever you want to the log message
log_message('error', '404 Page Not Found --> '.$page);
}
echo $this->show_error($heading, $message, 'error_404', 404);
exit;
}
}
If you keep getting stuff like favicon.ico, there's a good chance this is your fault, so you might want to look into that.
Just to clarify:
$_SERVER['HTTP_REFERER'] will give you the URL the page was requested from, so you can see where the request originated, whether it be on your site or elsewhere.
$_SERVER['REMOTE_ADDR'] should give you the IP address the request was made by
http://php.net/manual/en/reserved.variables.server.php
Brief Example:
if ($log_error)
{
$msg = '';
if (isset($_SERVER['HTTP_REFERER']))
{
$msg .= 'Referer was '.$_SERVER['HTTP_REFERER'];
}
else
{
$msg .= 'Referer was not set or empty';
}
if (isset($_SERVER['REMOTE_ADDR']))
{
$msg .= 'IP address was '.$_SERVER['REMOTE_ADDR'];
}
else
{
$msg .= 'Unable to track IP';
}
log_message('error', '404 Page Not Found --> '.$page.' - '.$msg);
}
I believe if you want this, you'd have to log it yourself by creating a custom 404 page and manually logging to the log file. You can access the IP address in PHP via $_SERVER['REMOTE_ADDR'].