Category: "PHP"

PHP session management and temporary file cleanup

By default, PHP manages sessions during requests. This simplifies installation, because no cron job is required. To allow performance tuning, several configuration settings are allowed to adjust the frequency of the session cleanup checking and execution.

In the default php.ini, there is the following line:

cd /path/to/sessions; find -cmin +24 | xargs rm

Added as a cron job, this can be executed at set intervals (every one to five minutes is probably good), to clear the session file storage directory of files older than 24 minutes. Once implemented the find command can replace the default PHP session cleanup, so those configuration variables can be set to never check for session timeouts. This will speed PHP processing, although it may be imperceptible. It will also improve your control of session length, because the checking and clearing are executed based on time, not PHP requests.

Name any temporary files required to support the session with the session id, plus an extension to indicate the type and use. For example 4365kh2kj54dfg2kjh12.wav, 4365kh2kj54dfg2kjh12.rpt.txt, 4365kh2kj54dfg2kjh12.rpt.html. This allows a second session cleanup script to check for the presence of the session file based on the temporary file’s basename, and delete the temporary files. The second session cleanup script can be included in the main PHP script, or run as a separate cron job, unless the contents of the temporary files could be considered protected data, in which case they should be removed as soon as the session is terminated.

If authentication (logout) is also used to destroy sessions, a mechanism should be provided to clear any related, sensitive, files.

dojo Form Demo

This is a very simple demonstration of a dojo form. Please use ‘View Source’ to view the code.

Supporting server-side PHP.

json.php

Returns the submitted input. Demonstrates a ’successful’ transaction.

<?php
header('Content-type: application/json');
echo <<<END
{"sText":"{$_REQUEST['sText']}"}
END;
?>

error.php

Returns a 503, service not available.

<?php
header("HTTP/1.0 503 Service Not Available");echo 'Server side error';
exit();
?>

timeout.php

Sleeps for 3 seconds to force a timeout.

<?php
sleep(3);
?>

PHP and javascript timestamper

This is an extension of an earlier script to demonstrate the difference in execution time of preg_replace and trim.

The objective of this demonstration is to show a quick time check method to determine the following:

  • Time required for PHP to process all statements
  • Time required for javascript to process all statements

This code is valuable for complex pages, specifically RIA pages, to assist engineers in finding ways to make the page display more quickly.


/* First line of the PHP script */
$fStartPHP=microtime(true);

/* Beginning of the HTML */
echo '<html>';

/* This captures the time the first javascript statement was executed */
echo '<script>var d=new Date();var jsStart=d.getTime();var jsEnd;</script>';

/* This captures the time the page has finished loading.  If other code is executed prior to the page being considered fully rendered and functional, the EndLoad function should be called after the last statement */ 
echo '<script>function EndLoad(){var d=new Date();jsEnd=d.getTime();jsElapsed=jsEnd-jsStart;document.getElementById(\'jsStartDisplay\').innerHTML=jsStart;document.getElementById(\'jsEndDisplay\').innerHTML=jsEnd;document.getElementById(\'jsElapsedDisplay\').innerHTML=jsElapsed;}</script>';

/* Body tag */
echo '<body onload="EndLoad()">';

/* At the end of the PHP script */
dd
$fEndPHP=microtime(true);
$fPHPElapsed=$fEndPHP-$fStartPHP;
echo 'PHPStartTime: ';printf("%f",$fStartPHP);echo '<br />'."\n";
echo 'PHPEndTime: ';printf("%f",$fEndPHP);echo '<br />'."\n";
echo 'PHPElapsed: ';printf("%f",$fPHPElapsed*1000000);echo ' microseconds <br />'."\n";
echo '<hr />';
echo 'HTML/JSStartTime: <span id="jsStartDisplay"></span><br />'."\n";
echo 'HTML/JSEndTime: <span id="jsEndDisplay"></span><br />'."\n";
echo 'HTML/JSElapsedTime: <span id="jsElapsedDisplay"></span>&nbsp;microseconds<br />'."\n";
echo '</body>';
echo '</html>';

Risks of Web-Based Application Management

Many web applications can be configured through the application. This is extremely valuable, especially for users that don’t have SSH access and don’t want to use FTP. The danger is that in order for web access to work, the web server must have write privileges into the directories. This creates a security risk.

Set the file permissions to 644, and the owner to the account owner, not the web server. This has an added benefit of limiting write privileges for configuration files to people with SSH/FTP access, not just application administration.

Try to set up the web server such that requests for files in compiled or cached template directories are denied for all users. In many cases, this will work, because template files are often included into other files at runtime. In the event that malicious files are placed in the directory, they cannot be served.

Remove the application name and version data from the page source. Suppress the delivery of detailed web server headers. The less information delivered, the better.

Change the admin access URLs from the default or standard names (such as admin), to something else. Delete or rename the installation directory or files. Be sure to use secure passwords.

Always disable directory display, to prevent people from browsing through the file system.

Be sure the server software is up to date, use mod_security (modsecurity.org), keep PHP up-to-date, and especially, the applications. Monitor the access and error logs. Backup the database and filesystem frequently (automate it). Periodically, SSH in to check the filesystem.

dojo - Smarty - PHP - Synchronizing client- and server-side validation

The following architecture with Smarty and dojo allows you to the client and server synchronized for validation for RIA/PHP applications.

Each input has 4 characteristics defined in a (PHP) .ini file -

V_input_name = regExp (usually includes length)
L_input_name = max length
R_input_name = true or false (required or not)
T_input_name = type of input data in database, used to support documentation



Each input also has 3 characteristics defined in a Smarty .conf file, and there is a .conf file for every language (.ini be under languages)

E_input_name = error message
I_input_name = invalid message
P_input_name = prompt message

Smarty constructs the input tags like so:

<input type="text" dojoType="dijit.form.ValidationTextBox"
    name="input_name" id="input_name"
    regExp="{#V_input_name#}"   
    errorMessage="{#E_input_name#}"
    promptMessage="{#P_input_name#}"
    invalidMessage="{#I_input_name#}"
    length="{#L_input_name#}" />



There is a simple javascript validation that accepts an array of inputs and tests if they are valid with input_name.isValid(), displaying input_name.errorMessage if not, and cancelling the submit.

On the server side, there is a loop that tests the inputs against the same strings:

foreach ($aInput as $k => $v)
  if (isset($aIni['V_'.$k]))
  { 
    $sInput=trim($v); 
    if (isset($aIni['R_'.$k])
    if (($aIni['R_'.$k]=='true') && ($sInput=='')) /* Test for required */
      return false;
    if (!filter($aIni['V_'.$k],$v))  /* flter ensures data complies with regexp */
        return false;
   }



This allows the client-side code to help the user enter valid data, and allows the server-side code to protect the server by disallowing or discarding data that isn’t valid.

Please note that page-level validation, where the required state and content of data may vary based on other inputs must be reflected at both the client and server side.