System of logs for my site - php

I create a small class for save the logs of my website. My log class :
class Logs {
public static function writeFile($message)
{
$log_path = '/home/vagrant/Workspace/symfony/app/logs';
// Set path:
$log_path .= '/' . date('Ymd');
$log_path .= '.log';
$s_message = date("Y-m-d H:i:s") . ' (' . microtime(true) . ') ' . $message;
$s_message .= "\n";
file_put_contents($log_path, $s_message, FILE_APPEND);
}
public static function logInfo($s_message)
{
self::writeFile($s_message);
}
}
And I call the static method in my controller :
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$categories = $em->getRepository('EnsJobeetBundle:Category')->getWithJobs();
$test = array(
'1'=>'1',
'2'=>'2',
'3'=>'3'
);
Logs::logInfo(print_r($test));
return $this->render('EnsJobeetBundle:Job:index.html.twig', array(
'categories' => $categories
));
}
The problem is that : in my view it's show this $test array and in my log is write only the first value of array, so the value 1.
What I'm doing wrong? Help me please! Thx in advance!

In accordion with the doc:
If you would like to capture the output of print_r(), use the return
parameter. When this parameter is set to TRUE, print_r() will return
the information rather than print it.
Use this:
Logs::logInfo(print_r($test, true));
instead of:
Logs::logInfo(print_r($test));
hope this help
I suggest you to use Monolog for this task
http://symfony.com/doc/current/cookbook/logging/monolog.html

print_r has second parameter: return. Wich means will print_r() returns it's output, or just display it. It's false by default
So you need to try
Logs::logInfo(print_r($test,true));

Related

Query log in codeigniter using hook

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();

fwrite put table with foreach

I want to make html file that while be a ip adress and insert what client do via $_SERVER
My problem is that i cant make table in that file so code is this
FTP
public static function Write($Wfile, $Wtext)
{
$open = fopen($Wfile, "w+");
fwrite($open, $Wtext);
}
File to create log
public function __construct()
{
chdir("Log");
$this->_file = $_SERVER['REMOTE_ADDR'] .".html";
if(!is_file($this->_file)){
ftpFile::Write($this->_file,$this->Standards());
}
public function Standards()
{
$html = "<html>\r\n <body>\r\n <table cellpadding='10'>";
return $html;
}
AND WHAT I WANT TO INSERT NOW
public function Set()
{
$indicesServer = array(
'PHP_SELF',
'argv',
'argc',
'GATEWAY_INTERFACE',
'SERVER_ADDR',
'SERVER_NAME',
......
foreach ($indicesServer as $arg){
return '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>';
}
so i try return, echo, print, file put content and i only get one result and that is last in my array.
ONCE Again i want to create log for user that come to my site and everthing inside $_SERVER write one time when sesion_id active and every where client go i want to insert and what $_POST insert in that file. Many of that i do only this is need to be fixed... TNX all
Your bottom code snippet doesn't work because you are attempting to return inside foreach loop: you can only return from a function once. Try this:
public function Set()
{
$indicesServer = array(
'PHP_SELF',
'argv',
'argc',
'GATEWAY_INTERFACE',
'SERVER_ADDR',
'SERVER_NAME',
......
$ret = "";
foreach ($indicesServer as $arg)
$ret .= '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>';
return $ret;
}

Accessing variable stored in class from another file

I would like to access the $new_id variable in the method below (from public class youth_teams) from an outside file but I can't figure out how. I have it printing the lastInsertID correctly from inside the file which contains the method but would like to be able to access the variable in other files also.
public function addTeam(
$team_name,
&$error
) {
$query = $this->pdo->prepare('INSERT INTO `' . $this->table . '` (
`team_name`
) VALUES (
:team_name
)');
$query->bindParam(':team_name', $team_name);
$query->execute();
print_r($query->errorInfo());
print $this->pdo->lastInsertID();
$new_id = $this->pdo->lastInsertID();
return $new_id;
}
Here's the code I've tried from the OTHER FILE:
sw::shared()->youth_teams->addTeam (
$team_name,
$error
);
$temp_two = sw::shared()->youth_teams->addTeam->pdo->lastInsertID();
echo "new id: " . $temp_two . "<br>";
Of course that is not working... What's the correct path to access $new_id?
It should be:
$temp_two = sw::shared()->youth_teams->addTeam($team, $error);
addTeam() is a function that returns $new_id, so you need to call it with ().
If you really want to be able to access $new_id directly, you can declare it global:
public function addTeam(
$team_name,
&$error
) {
global $new_id;
...
What was wrong with this?
$sw = new sw();
$temp_two = $sw->addTeam( $team, $error );
echo "new id: " . $temp_two . "<br>";
If you can call sw::shared() from the outside file, you can assign the object.
I probably am not fully understanding your code, if not, please fully explain the following:
sw::shared()->youth_teams->addTeam( $team, $error );
// 1. What does the shared() method do?
// 2. What is the youth_teams property?
If it's needed, might I suggest adding the assignment directly into the addTeam() function and use the above format to return the id only.

Warning: Missing Argument 1

I am having some problems with my php code: All information returns but I cannot figure out why I am getting the error. For my index page I only inluded the line of code that is actually using that class there really is no other code other than some includes. Im sure it is how I built my __contstruct but i am not sure of the approriate way of doing it. I am missing something in how it is being called from the index page.
This line of code for my __construct works w/o error but I do not want the variable assigned in my class.
public function __construct(){
$this->user_id = '235454';
$this->user_type = 'Full Time Employee';
}
This is my Class
<?php
class User
{
protected $user_id;
protected $user_type;
protected $name;
public $first_name;
public $last_name;
public $email_address;
public function __construct($user_id){
$this->user_id = $user_id;
$this->user_type = 'Full Time Employee';
}
public function __set($name, $value){
$this->$name = $value;
}
public function __get($name){
return $this->$name;
}
public function __destroy(){
}
}
?>
This is my code from my index page:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$employee_id = new User(2365);
$employee_type = new User();
echo 'Your employee ID is ' . '"' .$employee_id->user_id. '"' . ' your employement status is a n ' . '"' .$employee_type->user_type. '"';
echo '<br/>';
?>
The problem is:
$employee_type = new User();
the constructor expect one argument, but you send nothing.
Change
public function __construct($user_id) {
to
public function __construct($user_id = '') {
See the outputs
$employee_id = new User(2365);
echo $employee_id->user_id; // Output: 2365
echo $employee_id->user_type; // Output: Full Time Employee
$employee_type = new User();
echo $employee_type->user_id; // Output nothing
echo $employee_type->user_type; // Output: Full Time Employee
If you have one user, you can do this:
$employer = new User(2365);
$employer->user_type = 'A user type';
echo 'Your employee ID is "' . $employer->user_id . '" your employement status is "' . $employer->user_type . '"';
Which output:
Your employee ID is "2365" your employement status is "A user type"
I'm no PHP expert, but it looks like you are creating 2 new instances of class user, and on the second instatiation, you are not passing the user_id into the constructor:
$employee_id = new User(2365);
This, it would seem to me, is creating a new instance of User and assigning this instance to the variable $employee_id - I don't think this is what you want though?
$employee_type = new User();
This looks like you're instantiating another instance of User and assigning it to variable $employee_type - but you have called the constructor User() without passing in an ID as is required - hence the error (missing argument).
The reason your return script contents look OK is because the first instance of the User class has an ID (because you passed it in) and the second one has an employee type because this is set in the constructor.
Like I say, I don't know PHP but I'm guessing you want something more along the lines of:
$new_user = new User(2365);
echo 'Your employee ID is ' . '"' .$new_user->user_id. '"' . ' your employement status is a n ' . '"' .$new_user->employee_type. '"';
Here, you are instantiating a single instance of your user class assigned to the variable $new_user, and then accessing the properties of that single instance.
EDIT: .....Aaaaaaaaand - I was too slow :-)

Passing Variables from one functiion to another

I have 4 files. I am trying pass my fetch results through a function to another page. My code is below:
File actions.php
public function getAction($action, $page, Array $vars){
if(!empty($action)){
$action = strtolower($action);
$path = $page.'/'.$action.'.php';
$currentTemplate = $this->loadActionTemplate($path);
return Array($currentTemplate, $vars);
}
else{
$action = strtolower($action);
$path = $page.'/default.php';
$currentTemplate = $this->loadActionTemplate($path);
return ($currentTemplate);
}
}
File news.php(controller)
$file = VIEWS_PATH.strtolower($this->template) . '.php';
if (file_exists($file)){
$currentQuery = $newsModel->viewQuery($selectQuery,$returnAll);
include_once($file);
}
}
File news.php(Main view)
$factory = new Actions_Factory();
$factory->getAction($action, $page, $currentQuery);
File view.php(sub View)
print_r($currentQuery);
I can't get $currentQuery to print out the mysql dump on view.php but $currentQuery prints out fine on news.php. I am doing something wrong and can't figure out what it is.
Any help would be much appreciated.
Thanks in Advance
$factory->getAction($action, $page, $currentQuery);
print_r($currentQuery);
You set $currentQuery to getAction(), but this function return result if you want function affect on argument you have to use assign by reference!
Insert "&" in $var to assign variable by reference
public function getAction($action, $page, Array **&$vars**){

Categories