Showing posts with label Web. Show all posts
Showing posts with label Web. Show all posts

Sunday, March 15, 2015

Logging To File Or Email In PHP

Logging is one of the most important things in software engineering to record important code execution, as well as for debugging.

This is a simple PHP function for logging error and info, by sending email notification or logging to file, with the option to record a different timezone:

<?php

/**
* Logs an error.
*/
function logError($logMessage, $sourceFile)
{
    logInfo($logMessage, $sourceFile, "", true);
}

/**
* Logs an information.
*/
function logInfo($logMessage, $sourceFile, $logTtle = "", $isError = false)
{
    $logEmail       = "admin@example.com";      // Email address to send the logging message. Set to empty to disable it.
    $logFile        = "";                       // File name to store the logging message. Set to empty to disable it.
    $logTimezone    = "Europe/London";          // Set the additional datetime timezone shown in the logging message. Put empty to only show the default.
    
    $now            = new DateTime();           // Get current datetime in the default timezone.
    
    $logMsg = '[' . $now->format("Y-m-d H:i:s e") . ']' . "\r\n" . '[' . $sourceFile . ']' . "\r\n" . $logMessage . "\r\n\r\n";
    
    if ($logTimezone != "")
    {
        // Convert $now to the provided timezone and append at front as additional datetime.
        $now->setTimezone(new DateTimeZone($logTimezone));
        $logMsg = '[' . $now->format("Y-m-d H:i:s e") . '] ' . $logMsg;
        // ==
    }
    
    if ($logFile != "") {
        if ($isError)
            error_log($logMsg, 3, $logFile);
        else
            file_put_contents($logFile, $logMsg, FILE_APPEND | LOCK_EX);
    }
    
    if ($logEmail != "") {
        if ($isError)
            error_log($logMsg, 1, $logEmail);
        else
            mail($logEmail, $logTtle, $logMsg, "From: Notification Admin <noti@example.com>");
    }
}

Usage example:

<?php

try
{
    ...
    ...
    logInfo("Process completed successfully.", __FILE__, "Process Completed");
}
catch(Exception $e)
{
    logError("Process Exception: " . $e->getMessage() . ". Exception on line: " . $e->getLine(), __FILE__);
    exit;
}
?>


If you find this post helpful, would you buy me a coffee?


Tuesday, March 10, 2015

Update An Existing Configuration File In PHP

In PHP, it's a widely used practice to set a site's configuration details by defining constants in a separate "config" file.

This config file mostly contains important data such as security keys, database connections, paths, debug and logging information, and many more.

Normally, the config file contents are manually set by hand. However, we can also update or add contents from another new config file into an existing config file, which is being demonstrated in the following script. This script will update an existing defined constant with the new value, or add the constant if it doesn't exist. (Please change the FOO_CONFIG and NEW_FOO_CONFIG constants on top to your file path):

<?php

// Define the foo config file paths.
define('FOO_CONFIG',     __DIR__ . '/foo-config.php');          // The existing foo config file.
define('NEW_FOO_CONFIG', __DIR__ . '/new-foo-config.php');      // The new foo config file.
// ==

updateFooConfig();
return;

/**
* Updates NEW_FOO_CONFIG contents into existing FOO_CONFIG file.
*/
function updateFooConfig()
{
    try
    {
        $fooConfig        = file_get_contents(FOO_CONFIG);              // Read from existing FOO_CONFIG contents into string.
        $newFooConfig     = file_get_contents(NEW_FOO_CONFIG);          // Read from the NEW_FOO_CONFIG contents into string.
        
        $newFooConfigLine = strtok($newFooConfig, "\r\n");              // Read each line in the NEW_FOO_CONFIG string.
        while ($newFooConfigLine !== false)
        {
            // Note: Patterns must be enclosed with delimiters, e.g. "/".
            
            if (preg_match("/\s*define\s*\(\s*('.*?')\s*,\s*('*.*?'*)\s*\)\s*;\s*/", $newFooConfigLine, $matches))              // If the NEW_FOO_CONFIG line is a define(...).
            {
                if (preg_match("/\s*define\s*\(\s*" . $matches[1] . "\s*,\s*('*.*?'*)\s*\)\s*;\s*/", $fooConfig, $matches2))    // If FOO_CONFIG string contains the same define(...) constant.
                    $fooConfig = str_replace(trim($matches2[0]), trim($matches[0]), $fooConfig);                                // Replace FOO_CONFIG string with this NEW_FOO_CONFIG line string.
                else
                    $fooConfig = $fooConfig . PHP_EOL . $newFooConfigLine;                                                      // Append this NEW_FOO_CONFIG line to FOO_CONFIG string if not found.
            }

            $newFooConfigLine = strtok( "\r\n" );                       // Read next line in NEW_FOO_CONFIG string.
        }
        
        if (file_put_contents(FOO_CONFIG, $fooConfig) === false)        // Wrtie the FOO_CONFIG string back to it's file, overwrite existing.
            throw new Exception("Foo config file '" . FOO_CONFIG . "' cannot be written.");
    }
    catch(Exception $e)
    {
        // TODO: Throw or log the exception.
        exit;
    }
}


If you find this post helpful, would you buy me a coffee?


Thursday, August 22, 2013

IIS7: Setup Virtual Folder

These are the steps to setup a virtual folder in IIS 7:


1. Set security permissions for the folder (NETWORK SERVICE permission is required if access through browser).
2. Add a virtual directory to the folder.
3. Authentication > Windows Form > Enabled, the rest disabled.
4. Allow Directory Listing.
5. After saving the IIS, if a Web.config created inside the folder, add this line above the <mimeMap...> line, as follows:
<remove fileExtension=".*" />
<mimeMap fileExtension=".*" mimeType="application/octet-stream" />

(this is to remove any conflicting mimeMap extensions from this folder's config)



If you find this post helpful, would you buy me a coffee?


Tuesday, October 4, 2011

Online Syntax Highlighting Using ToHtml.com

Just want to share a source code syntax highlighting tool I discovered recently that is easy to use and supports many different languages, even the rare ones.

The steps are rather straight forward. Just go to ToHtml.com, paste your code inside the "Source Code" panel. Then choose your language type and hit "Highlight". In a short while your code will be formatted into the "HTML code" panel, which you can just copy and paste directly into your web site or blog. In addition, you can also select the style you want, and preview the formatted output.

There is no worries on any special characters like > or <, it will take care for you as well.

Originally I was trying to use SyntaxHighlighter, but after spending much time troubleshooting, it just won't work on this blog. I'm not sure where I did wrong, maybe I will give it another shot when I have more time to spare. However, for now, I think this online tool already can fulfill my needs. Cheers :)

If you find this post helpful, would you buy me a coffee?