how to create a logfile in php?

php write log to text file
how to create activity log in php
php log to console
php write to file
php log() function
php logging library
php error_log not working
php trace log file

I want to create a logfile for my system to register/log every action they do inside the system. But I have no idea how to do it.

For example, I have this php code that does the login function.

public function hasAccess($username,$password){
    $form = array();
    $form['username'] = $username;
    $form['password'] = $password;


    $securityDAO = $this->getDAO('SecurityDAO');
    $result = $securityDAO->hasAccess($form);
    //var_dump($form);
    //var_dump($result);
    if($result[0]['success']=='1'){
        $this->Session->add('user_id', $result[0]['id']);
        //$this->Session->add('username', $result[0]['username']);
        //$this->Session->add('roleid', $result[0]['roleid']);
        return $this->status(0,true,'auth.success',$result);
    }else{
        return $this->status(0,false,'auth.failed',$result);
    }
}

now I want to create a logfile entitled 'the date today', then when that functions is used for loging in, it will write that user has logged in, the same with other functions. But I only want a single file for every day.

Could anyone be kind enough to guide and teach me how I should do my codes?

To write to a log file and make a new one each day, you could use date("j.n.Y") as part of the filename.

//Something to write to txt log
$log  = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
        "Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
        "User: ".$username.PHP_EOL.
        "-------------------------".PHP_EOL;
//Save string to log, use FILE_APPEND to append.
file_put_contents('./log_'.date("j.n.Y").'.log', $log, FILE_APPEND);

So you would place that within your hasAccess() method.

public function hasAccess($username,$password){
    $form = array();
    $form['username'] = $username;
    $form['password'] = $password;

    $securityDAO = $this->getDAO('SecurityDAO');
    $result = $securityDAO->hasAccess($form);

    //Write action to txt log
    $log  = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
            "Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL.
            "User: ".$username.PHP_EOL.
            "-------------------------".PHP_EOL;
    //-
    file_put_contents('./log_'.date("j.n.Y").'.txt', $log, FILE_APPEND);

    if($result[0]['success']=='1'){
        $this->Session->add('user_id', $result[0]['id']);
        //$this->Session->add('username', $result[0]['username']);
        //$this->Session->add('roleid', $result[0]['roleid']);
        return $this->status(0,true,'auth.success',$result);
    }else{
        return $this->status(0,false,'auth.failed',$result);
    }
}

How to log errors and warnings into a file in php?, The ini_set(“log_errors”, TRUE) command can be added to the php script to enable error logging in php. The ini_set('error_log', $log_file) command can be added to the php script to set the error logging file. Further error_log($error_message) function call can be used to log error message to the given file. Creating logging functionality in php application is very easy.You just need to create a single log.php file into your application.You need to import this file and use it any where in application. PHP Log into The File Let’s add the below code into the log.php file.

create a logfile in php, to do it you need to pass data on function and it will create log file for you.

function wh_log($log_msg)
{
    $log_filename = "log";
    if (!file_exists($log_filename)) 
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    // if you don't add `FILE_APPEND`, the file will be erased each time you add a log
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}

error_log - Manual, $extra_headers ]]] ) : bool. Sends an error message to the web server's error log or to a file. two monitors setup. One for your browser and IDE and the other for viewing the log files update live as you go. Create or update the registry key Function for logging to a file. The function that follows takes a message and an optional path to a log file as arguments. If no path is given, the log is written to the file specified in DEFAULT_LOG. The message is written along with the remote address, requested script, and the time of the request.

Please check with this documentation.

http://php.net/manual/en/function.error-log.php

Example:

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "operator@example.com");
}

// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

PHP Logging Basics - The Ultimate Guide To Logging, This guide explores the basics of logging in PHP including how to configure Here's where you can find your php.ini file in common distributions of Linux. Notices and warnings can indicate variables aren't being created in the way you​  now I want to create a logfile entitled ‘the date today’, then when that functions is used for loging in, it will write that user has logged in, the same with other functions. But I only want a single file for every day.

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d')) as filename. And now you should know where to start... :)

How To Create PHP Logfile and Write Error Log, This Tutorial providing a php function which will create a log file in application.​You can call this fucntion to log method debug information. pakainfo website focuses on all web language and framework tutorial PHP, Laravel, Codeigniter, Nodejs, API, MySQL, AJAX, jQuery, JavaScript, Demo How to create a logfile in PHP | Pakainfo

Please check this code, it works fine for me.

$data = array('shopid'=>3,'version'=> 1,'value=>1');  //here $data is dummy varaible

error_log(print_r($data,true), 3, $_SERVER['DOCUMENT_ROOT']."/your-file-name.log");

//In $data we can mention the error messege and create the log

Write to a log file with PHP – Redips spideR Net, After writing custom PHP “log” function several times I finally decided to create a simple Logging PHP class. First call of lwrite method will open log file implicitly and write line to the file. Every other lwrite will use already  Hope this code and post will helped you for implement log file in php. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section.

PHP Log Files: Tips for Developers, Here are some pointers on how to configure your log files to help maximize their value. Error Log Confguration. Error logs represent the most basic form of logging​;  After writing custom PHP “log” function several times I finally decided to create a simple Logging PHP class. First call of lwrite method will open log file implicitly and write line to the file. Every other lwrite will use already opened file pointer until closing file with lclose.

PHP error_log() Function, The error_log() function sends an error message to a log, to a file, or to a mail sent to PHP's system logger, using the OS' system logging mechanism or a file,  PHP arrays and objects can be converted to JSON string using json_encode(). Likewise, JSON can be reconstituted as a native PHP construct by using json_decode(). A few code examples follow that demonstrate the functions first, then using them to log and parse an entry. Example: Using the json_encode() function with an associative array

How to create logs with PHP - Web Services Wiki, When MySQL is unavailable, saving information to flat files is a good alternative. Logging to a MySQL database. We  PHP Create File - fopen() The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

Comments
  • Better to log to db, your code is 1 line away from db access, why create a separate function to write to a file, but what have you tried?
  • Yup, I have an xml file where it calls out the stored proc. No, I haven't tried anything yet. 'Cause I don't know where to start. I was told to log the events whenever a function is called.
  • what is the use of .php_eol? Will try this code. Thank you!
  • PHP_EOL is like doing "\n" or "\r\n" dependent on which os platform. I hate lots of \n\n\n\n's ;p
  • Works like a charm! Thank you so much for the big help, Mr. Lawrence!
  • I tried to put my system on a linux based computer and now there's a problem with the log file regarding permissions. How can I fix it?
  • Definitely wouldn't store plain-text passwords, period, including log files.
  • How do I write it? Do you mind if you could give me a sample code? If it's not too much to ask. Thank you.
  • In above code error_log line is enough to create a new log file in your root folder, print_r($data,true) data mention what you are really want to print in that log file.
  • How would you write this in OOP PHP?
  • @TRS7 I am not sure, sorry. I call set_error_handler in every one of my php files separately.