I am trying to build an exception handler for codeIgniter that triggers when an error occurs, and it will record all input that caused the exception and the output the exception gave in a clean neat format in a text file.
As far I could only record the exception in log file using log function. in the error_db template file I extracted the message value and inserted it into log file.
<div id="container">
<h1><?php echo $heading; ?></h1>
<?php echo $message;
$formatted_msg = str_replace('</p>','',$message);
$formatted_msgs = explode('<p>',$formatted_msg);
$messages = $formatted_msgs[1].' --> '.$formatted_msgs[4].' --> '.$formatted_msgs[5];
log_message('error',$messages);
?>
</div>
I want to show the result like: What function,what input and which line caused the exception and output produced. Now I am getting data like
ERROR - 2019-04-16 15:28:40 --> Error Number: 1054 --> Filename: file_path/system/database/DB_driver.php --> Line Number: 691
I followed this method and got the answer. https://stackoverflow.com/a/15860744/11367846
And added some customization for my requirement. In the controller page in exception catch added code for customized log.
public function controller_method( )
{
try
{
// normal flow
}
catch( Exception $e )
{
$trace = $e->getTrace();
$result = 'Exception: "';
$result .= $e->getMessage();
$result .= '" # ';
if($trace[4]['file'] != '') {
$result .= ' File : '.$trace[4]['file'].'::: Line : '.$trace[4]['line'].' ::: Source :'.$trace[5]['class'].' -> '.$trace[5]['function'].' ::: Function : '.$trace[4]['class'].' -> '.$trace[4]['function'].' ::: Inputs :'.http_build_query($trace[4]['args']);
}
log_message( 'error', $result );
}
}
Related
How I export my data in qif format. I didn't get any idea, how I Can?
Please help me to find out the way.
try this
//i don't know what is the qif text format, but with this you can write a file
write_file.php
public function write_qif( $info ){
$this->load->helper(array('file','download'));
$_info = $this->some_model->get_info($info);//return object
$qif_text = '
!Type:'.$_info->type.'//BANK
D'.$_info->date1.'//03/03/10
T-379.00
P'.$_info->city.'//CITY OF
^
D'.$_info->date2.'//03/04/10
T-20.28
P'.$_info->maket_place.'//YOUR LOCAL SUPERMARKET
^
D'.$_info->date3.'//03/03/10
T-421.35
P'.$_info->product.'//...WATER UTILITY
';
if ( ! write_file('./path/to/file.qif', $_info)){
echo 'Unable to write the file';
}
else{
$data = file_get_contents(.'/path/to/file.qif');
$name = 'myqiffile.qif';
force_download($name, $data);
echo 'File written!';
}
}
my intention is simple i just want to get my pages in different formats
e.g
www.my-site.com/product-name.html -- will load the page in html
but i want a json object when i type
www.my-site.com/product-name.json
if their is any event that magneto dispatch before rendering 404 page, that can be very helpful
or i have to rewrite app/code/core/Mage/Cms/controllers/indexcontroller.php
more or less
public function defaultNoRouteAction()
{
$this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
$this->getResponse()->setHeader('Status','404 File not found');
$this->loadLayout();
$this->renderLayout();
}
but i don't know how.
I've done something similar, exporting product data when calling an product-url with .xml instead of .html.
I've added an observer listening on product save event, that adds the product-xml URL into core_url_rewrite.
In that event, you have replace .htm(l) with .xml
e.g.
product-name.htm -> catalog/product/view/id/4 -> load product with ID 4 and render product view template, magento core
product-name.xml -> mycustommodule/product/view/id/4 -> load product with ID 4 and render XML, custom module
So you have to add another module called "mycustommodule" that handles the xml output.
Cheers!
i solution that i found is following,it work perfectly but didn't know for sure is it the MAGNETO-WAY
i rewrite Mage_Cms_IndexController noRoute Method,
public function noRouteAction($coreRoute = null) {
// getting current url
$url = Mage::helper('core/url')->getCurrentUrl();
if ( strstr($url,".jsonp") || strstr($url,".json") || strstr($url,".xml") ) {
// geting file-type like json / xml
$format = substr(strrchr($url, "."),1);
// product-handle
$elem = substr( strrchr($url, "/"),1, strpos( strrchr($url, "/") , ".")-1 );
switch ($format) {
case 'json': case 'JSON': case 'jsonp': case 'JSONP':
$this->getResponse()->setHeader('Content-type', 'application/json'); break;
case 'xml': case 'XML':
$this->getResponse()->setHeader('Content-type', 'application/xml'); break;
}
// loding product byproduct-handle
$rewrite = Mage::getModel('core/url_rewrite')->setStoreId(Mage::app()->getStore()->getId())->loadByRequestPath($elem . ".html");
$pid = $rewrite->getProductId();
$cat = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->loadByAttribute('url_key', $elem );
if (strpos($url,"hs_review")) { echo Mage::getModel("Hs_Json/review")->wrapper($pid,$format);return;}
if ( $pid ) { echo Mage::getModel("Hs_Json/product")->wrapper($pid,$format);return; }
if ( $cat ) { echo Mage::getModel("Hs_Json/category")->wrapper($cat->getId(),$format);return;}
} else {
$this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
$this->getResponse()->setHeader('Status','404 File not found');
$pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_NO_ROUTE_PAGE);
if (!Mage::helper('cms/page')->renderPage($this, $pageId)) {
$this->_forward('defaultNoRoute');
}
}
}
}
My report does not write exactly accentuated letters ( french ) , so there are unreadable characters displayed on the report. The runReport.php file is :
<?php
define("ROOT_PATH", "../");
require_once ROOT_PATH . 'config.inc.php';
require_once("java/Java.inc");
class runReport {
function runReport($report, $param, $output) {
$pth = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"];
$path_parts = pathinfo($pth);
$imageURLPrefix = $path_parts['dirname'] ."/images/";
session_start();
$here = getcwd();
$ctx = java_context()->getServletContext();
$birtReportEngine = java("org.eclipse.birt.php.birtengine.BirtEngine")->getBirtEngine($ctx);
java_context()->onShutdown(java("org.eclipse.birt.php.birtengine.BirtEngine")->getShutdownHook());
try{
$thereport = $birtReportEngine->openReportDesign(RP_REPORT.$report);
$task = $birtReportEngine->createRunAndRenderTask($thereport);
$task->setParameterValue("province", new java("java.lang.Integer", read_post_int("province"));
$taskOptions = new java("org.eclipse.birt.report.engine.api.HTMLRenderOption");
$outputStream = new java("java.io.ByteArrayOutputStream");
$taskOptions->setOutputStream($outputStream);
$taskOptions->setOutputFormat("html");
$ih = new java( "org.eclipse.birt.report.engine.api.HTMLServerImageHandler");
$taskOptions->setImageHandler($ih);
$taskOptions->setEnableAgentStyleEngine(true);
$taskOptions->setBaseImageURL($imageURLPrefix . session_id());
$taskOptions->setImageDirectory($here . "/images/" . session_id());
$task->setRenderOption( $taskOptions );
$task->run();
$task->close();
}
catch (JavaException $e) {
echo $e; //"Error Calling BIRT";
}
echo $outputStream;
}
}
?>
So how to make the report support utf-8 encoding ?
Don't know PHP, but this could just be a problem of your encoding HTTP header. What does the HTML source generated by BIRT look like.
Does it contain a <meta charset="xxx"/> tag?
If it does, this should match the Content-Encoding HTTP header (sent by your server, probably settable with PHP).
I am working in codeigniter 2.4. I have to use google recaptcha in ony of my project.Below is my code.
// field validation
$this->form_validation->set_rules('recaptcha_challenge_field', 'Captcha Code', 'trim|required|xss_clean|callback_checkCaptcha');
The call back function is :
function checkCaptcha($captcha){
$resp = $this->recaptcha->recaptcha_check_answer ( $this->input->ip_address(), $this->input->post('recaptcha_challenge_field',true), $this->input->post('recaptcha_response_field',true));
if($resp->is_valid)
{
return true;
}
else
{
$this->form_validation->set_message('checkCaptcha', 'Sorry Invalid captcha code');
return false;
}
}
But I am getting this error:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/offer.php
Line Number: 59
Please help me where I am going wrong .
Thanks.
I have updated my code and it works for me now. In the captcha library I have made the is_valid property public and then I replaced
if($resp->is_valid)
with
if($this->recaptcha->is_valid)
Now it works for me.
Thanks for all who responed my question.
public function captcha_verify(){
$form_response = $this->input->post('g-recaptcha-response');
$url = "https://www.google.com/recaptcha/api/siteverify";
$secretkey = "6LeBGG0UAAAAAEzWMaT0sOjPxcbNwQe7TiWWAknQ";
$response = file_get_contents($url."?secret=".$secretkey."&response=".$form_response."&remoteip=".$_SERVER["REMOTE_ADDR"]);
$data = json_decode($response);
print_r($data);
if (isset($data->success) && $data->success=="true") {
echo "Successfully Passed through captcha";
}
else{
echo "Please Fill captcha";
}
}
You need to provide your private key in here too as the first parameter:
$resp = $this->recaptcha->recaptcha_check_answer ($private_key, $this->input->ip_address(), $this->input->post('recaptcha_challenge_field',true), $this->input->post('recaptcha_response_field',true));
echo "<pre>";print_r($resp);die; #check the response array.
I am working in codeigniter 3.1.5. I have to use this code but not work for me but this code work for me in google recaptcha in google recaptcha in codeigniter 3.1.5.
this is my code for google recaptcha in codeigniter
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="ADD_YOUR_GOOGLE_SITE_KEY_HERE"></div>
function of google validate captcha
function google_validate_captcha() {
$google_captcha = $this->input->post('g-recaptcha-response');
$google_response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=your secret key here &response=" . $google_captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
if ($google_response . 'success' == false) {
return FALSE;
} else {
return TRUE;
}
}
Reference :: http://www.onlinecode.org/integrate-google-recaptcha-codeigniter-validation/
To be more clear, none of these lines in default language's general_lang.php work:
$lang['general_welcome_message'] = 'Welcome, %s ( %s )';
or
$lang['general_welcome_message'] = 'Welcome, %1 ( %2 )';
I expect an output like Welcome, FirstName ( user_name ).
I followed the second (not accepted) answer at https://stackoverflow.com/a/10973668/315550.
The code I write in the view is:
<div id="welcome-box">
<?php echo lang('general_welcome_message',
$this->session->userdata('user_firstname'),
$this->session->userdata('username')
);
?>
</div>
I use codeigniter 2.
You will need to use php's sprintf function (http://php.net/manual/en/function.sprintf.php)
Example from http://ellislab.com/forums/viewthread/145634/#749634:
//in english
$lang['unread_messages'] = "You have %1$s unread messages, %2$s";
//in another language
$lang['unread_messages'] = "Hi %2$s, You have %1$s unread messages";
$message = sprintf($this->lang->line(‘unread_messages’), $number, $name);
I extended Code CI_Lang class like this..
class MY_Lang extends CI_Lang {
function line($line = '', $swap = null) {
$loaded_line = parent::line($line);
// If swap if not given, just return the line from the language file (default codeigniter functionality.)
if(!$swap) return $loaded_line;
// If an array is given
if (is_array($swap)) {
// Explode on '%s'
$exploded_line = explode('%s', $loaded_line);
// Loop through each exploded line
foreach ($exploded_line as $key => $value) {
// Check if the $swap is set
if(isset($swap[$key])) {
// Append the swap variables
$exploded_line[$key] .= $swap[$key];
}
}
// Return the implode of $exploded_line with appended swap variables
return implode('', $exploded_line);
}
// A string is given, just do a simple str_replace on the loaded line
else {
return str_replace('%s', $swap, $loaded_line);
}
}
}
ie. In your language file:
$lang['foo'] = 'Thanks, %s. Your %s has been changed.'
And where-ever you want to use it (controller / view etc.)
echo $this->lang->line('foo', array('Charlie', 'password'));
Will produce
Thanks, Charlie. Your password has been changed.
This handles single 'swaps' as well as multiple
Also it won't break any existing calls to $this->lang->line.