Category Archives: Page Headers

PHP Scripts for param Page Headers

This PHP Script is used to validate and filter request values. It allows you to define a parameter or a list of parameters that must be read from POST or GET variables. param script can also filter values with a maximum length, discard values that seem to be used for SQL injection attempts and assume a default value for missing or invalid request values.-a param type can be an array or an object, not only a scalar value
- you can define custom function to set restriction for the values
- you can define a type casting for the param
- SQL INJECTION management.

 

 

<?php
/**
 *  @package Param
 *  @author Domenico Pontari <fairsayan@gmail.com>
 *  @copyright Copyright (c) 2009, Domenico Pontari
 *  @license http://opensource.org/licenses/bsd-license.php New and Simplified BSD licenses
 *  @version 1.0
 *
 *  This class allow you to define a parameter or a list of parameters that must be
 *  read from $_POST or $_GET variables. Features are:
 *  1. a param type can be an array or an object, not only a scalar value
 *  2. you can define custom function to set restriction for the values
 *  3. you can define a type casting for the param
 *  4. SQL INJECTION management
 *
 *  It follows a factory pattern: each param type
 *  must be an extended class of "param" base class
 */


 /**#@+
 * param types
 */

 define ('PARAM_DIM_SINGLE', 'single');
 define ('PARAM_DIM_ARRAY', 'array');
 define ('PARAM_DIM_ASSOCIATIVE', 'associative array');
 define ('PARAM_DIM_OBJECT', 'object');

 define ('PARAM_TYPE_BOOL', 'boolean');
 define ('PARAM_TYPE_INT', 'integer');
 define ('PARAM_TYPE_STRING', 'string');
 define ('PARAM_TYPE_AUTO', 'auto');

 define ('PARAM_CTRL_INPUT', 'input');

 define ('PARAM_INPUT_GET', 'get');
 define ('PARAM_INPUT_POST', 'post');
 define ('PARAM_INPUT_DEFAULT_VALUE', 'default value'); // value defined in the "value" attribute of "paramVars" class
 /**#@-*/

 /**
 *  required library
 *  @link http://www.phpclasses.org/package/5969-PHP-Tokenizer-split-strings-into-tokens.html
 */

 require_once ('tokenizer.php');

 /**
 *  @package Param
 */

 class param {
 /**
 *  @var string inclusion path for extended classes
 */

 static $includePath = '';

 protected $vars = false;
 function get() {return $this->vars;}

 /**
 *  @param paramVars|array
 */

 static function register ($vars) {
 if (!is_a($vars, 'paramVars')) $vars = new paramVars ($vars);
 if ($vars->refClass !== false) {
 $className = $vars->refClass . "Param";
 if (!class_exists($className)) {
 include_once ($includePath . "param_$vars->refClass");
 if (!class_exists($className)) trigger_error ('unableToFindParamClassExtension', E_USER_ERROR);
 }
 } else $className = 'param';
 $param = new $className ($vars);
 if ($param->get() === false) return false;
 return $param;
 }

 function __construct ($vars) {
 $this->set($vars);
 if ($this->vars->startGettingFromInput) $this->setValueFromURL();
 }

 /**
 *  @return void
 */

 function set($vars) {
 $this->vars = $vars;
 }

 protected function getVar ($varName) {
 if (!isset($this->vars->$varName)) trigger_error ('paramValueNotSetted');
 return $this->vars->$varName;
 }

 protected function setVar ($varName, $varValue) {
 $this->vars->$varName = $varValue;
 }

 function __get ($varName) {
 switch ($varName) {
 case 'value':
 case 'name':
 $result = $this->getVar ($varName);
 break;
 default:
 trigger_error ('paramAttributeNotFound', E_USER_ERROR);
 }
 return $result;
 }

 function __set ($varName, $varValue) {
 switch ($varName) {
 case 'value':
 $result = $this->setVar ($varName, $varValue);
 break;
 default:
 trigger_error ('unableToSetThisAttribute', E_USER_ERROR);
 }
 }

 function getDefaultValue () {
 return $this->vars->defaultValue;
 }

 /**
 *  @return string|false if no valid input is found false will be returned
 *
 *  if PARAM_INPUT_DEFAULT_VALUE is found it will return false as well
 */

 function getInputStringFromURL () {
 $result = false;
 $defaultValue = $this->getDefaultValue();
 foreach ($this->vars->inputList as $input) {
 if (($input == PARAM_INPUT_POST) &amp;&amp; (isset($_POST[$this->vars->name])))
 $result = $_POST[$this->vars->name];
 if (($input == PARAM_INPUT_GET) &amp;&amp; (isset($_GET[$this->vars->name])))
 $result = $_GET[$this->vars->name];
 if (($input == PARAM_INPUT_DEFAULT_VALUE) &amp;&amp; (isset($defaultValue)))
 return false;
 if ($result !== false) {
 if (self::sqlInjectionAttempted($result)) trigger_error ('sqlInjectionDetected', E_USER_ERROR);
 return $result;
 }
 }
 return $result;
 }

 function setValueFromURL () {
 $inputString = $this->getInputStringFromURL();
 if ($inputString !== false)
 $this->vars->value = $this->stringToValue($inputString);
 elseif (in_array(PARAM_INPUT_DEFAULT_VALUE, $this->vars->inputList)) {
 $defaultValue = $this->getDefaultValue();
 if (isset($defaultValue)) $this->vars->value = $defaultValue;
 }
 }

 protected function stringToValue ($string) {
 $value = self::splitInputString ($string, $this->vars->dimension);
 $value = self::castType ($value, $this->vars->type);
 if (isset($this->vars->maxLen)) {
 self::checkMaxLen ($value, $this->vars->maxLen, $newValue);
 $value = $newValue;
 }
 $value = $this->filter($value);
 if (!$this->validate($value)) trigger_error ('errorValidatingParam', E_USER_ERROR);
 return $value;
 }

 /**
 *  This function tell you if this param value is a default value so that
 *  you can omit it to define current state
 */

 function isInIrrelevantState () {
 $defaultValue = $this->getDefaultValue();
 if (!isset($defaultValue)) return false;
 if ($this->vars->value === $defaultValue) return true;
 return false;
 }

 /**
 *  Function to be extended
 *  @return mixed filtered value
 */

 function filter ($value) {return $value;}

 /**
 *  Function to be extended
 *  @return bool
 */

 function validate ($value) {return true;}

 static protected function splitInputString ($string, $dimension) {
 $result = $string;
 switch ($dimension) {
 case PARAM_DIM_OBJECT:
 case PARAM_DIM_ASSOCIATIVE:
 $result = json_decode ($result);
 break;
 case PARAM_DIM_ARRAY:
 $result = explode(",", $result);
 break;
 }
 return $result;
 }

 /**
 *  @param mixed
 *  @param int
 *  @param mixed cutted values
 *  @return bool
 */

 static protected function checkMaxLen ($value, $maxLen, &amp;$cuttedValue = NULL) {
 if (!is_scalar ($value)) {
 foreach ($value as $el)
 if (!checkMaxLen ($el, $maxLen)) return false;
 return true;
 }
 $oversize = (strlen($value) > $maxLen);
 if (gettype($value) != 'string') {
 $module = '1';
 for ($i = 1; $i < $maxLen; $i++) $module .= '0';
 $module = intval($module);
 $cuttedValue = $value % $module;
 } else $cuttedValue = substr($value, 0, $maxLen);
 return !$oversize;
 }

 /**
 *  Used to detect SQL injection attempted
 *  Criteria:
 *  1. found ('select', 'update', 'delete', 'insert') AND ('from')
 *  2. found ('execute', 'exec', 'cast') AND parenthesis
 *  @return bool
 */

 static protected function sqlInjectionAttempted ($string) {
 if (empty($string)) return false;
 $string = strtolower($string);
 $separators = array (',', '"', "'", "(", ")", " ");
 $tokenizer = new tokenizer ();
 $tokenizer->setLimits ($separators);
 $tokenizer->tokenize($string);
 $tokens = $tokenizer->getTokens(true);

 // First check
 $wordFound = false;
 foreach ($tokens as $token) {
 $wordFound = in_array($token, array('select', 'update', 'delete', 'insert'));
 if ($wordFound == true) break;
 }
 if (($wordFound)&amp;&amp;(in_array('from', $tokens))) return true;

 // Second check
 $wordFound = false;
 foreach ($tokens as $token) {
 $wordFound = in_array($token, array('execute', 'exec', 'cast'));
 if ($wordFound == true) break;
 }
 if (($wordFound)&amp;&amp;(in_array('(', $tokens))) return true;
 return false;
 }

 static protected function castType ($value, $type) {
 if (!is_scalar($value)) {
 foreach ($value as $name => $el)
 $value[$name] = self::castType ($el, $type);
 return $value;
 }

 if (($type == PARAM_TYPE_BOOL) || ($type == PARAM_TYPE_AUTO)) {
 if ($value === 'false') $value = false;
 if ($value === 'true') $value = true;
 }
 switch ($type) {
 case PARAM_TYPE_AUTO:
 if (is_numeric($value)) $type = PARAM_TYPE_INT;
 if (empty($value) || is_bool($value)) $type = PARAM_TYPE_BOOL;
 default:
 if (!settype ($value, $type)) trigger_error ('unableToCastParam', E_USER_ERROR);
 }
 return $value;
 }
 }

 /**
 *  @package Param
 */

 class paramVars {
 public $name;
 public $type = PARAM_TYPE_AUTO;
 public $value;
 public $dimension = PARAM_DIM_SINGLE;
 public $description = '';
 public $startGettingFromInput = true;

 /**
 *  @var string|false class name where are defined custom functions. If false
 *  base "param" class will be used
 */

 public $refClass = false;

 /**
 *  @var int you can decide if this param must be retrieve from $_GET, $_POST or both
 *  the order in the array is preserved: if something is found for the first input type
 *  the others are not followed
 */

 public $inputList = array(PARAM_INPUT_POST, PARAM_INPUT_GET, PARAM_INPUT_DEFAULT_VALUE);

 public $maxLen;

 public $defaultValue;
 public $defaultValueDescription = '';

 /**
 *  @var string HTML control type
 */

 public $controlType = PARAM_CTRL_INPUT;

 /**
 *  @param array an associative array with custom values
 */

 function __construct ($array = array()) {
 if (!is_array($array)) trigger_error ('varsToDefineParamMustBeAnArray', E_USER_ERROR);
 if (empty($array)) return;
 foreach ($this as $var => $value) {
 if (isset($array[$var])) $this->$var = $array[$var];
 }
 }
 }




?>

&amp;nbsp;

PHP QoS Bandwidth Throttler Page Headers

The output of a PHP is intercepted by setting a buffering handler that is called every time a given number of bytes are served to the user’s browser.It measures the time since the last time the PHP output buffer was flushed and hold on PHP for a while if the average download speed is above a given limit. This method allows the server not to clog up the bandwidth with file transfers only, and allow HTTP requests and normal traffic to pass through.

<?php

/**
 * QoS Bandwidth Throttler (part of Lotos Framework)
 *
 * Copyright (c) 2005-2010 Artur Graniszewski (aargoth@boo.pl)
 * All rights reserved.
 *
 * @category   Library
 * @package    Lotos
 * @subpackage QoS
 * @copyright  Copyright (c) 2005-2010 Artur Graniszewski (aargoth@boo.pl)
 * @license    GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007
 * @version    $Id$
 */


/**
 * Configuration interface.
 */

interface IThrottleConfig {}

/**
 * Configuration class.
 */

class ThrottleConfig implements IThrottleConfig
{
    /**
     * Burst rate limit in bytes per second.
     *
     * @var int
     */

    public $burstLimit = 80000;
   
    /**
     * Burst transfer rate time in seconds before reverting to the standard transfer rate.
     *
     * @var int
     */

    public $burstTimeout = 20;

    /**
     * Standard rate limit in bytes per second.
     *
     * @var int
     */

    public $rateLimit = 10000;
   
    /**
     * Enable/disable this module.
     *
     * @var bool
     */

    public $enabled = false;
}

/**
 * Another configuration class.
 */

class ThrottleConfigBySize implements IThrottleConfig
{
    /**
     * Maximal peak rate limit in bytes per second.
     *
     * @var int
     */

    public $burstLimit = 80000;
   
    /**
     * Size (in bytes) of the already transferred data wjile in burst rate transfer before reverting to standard transfer rate.
     *
     * @var int
     */

    public $burstSize = 2000;

    /**
     * Standard rate limit in bytes per second.
     *
     * @var int
     */

    public $rateLimit = 10000;
   
    /**
     * Enable/disable this module.
     *
     * @var bool
     */

    public $enabled = false;
}

/**
 * The main class.
 */

class Throttle
{
    /**
     * Last heartbeat time in microseconds.
     *
     * @var int
     */

    protected $lastHeartBeat = 0;
   
    /**
     * First (starting) heartbeat time in microseconds.
     *
     * @var int
     */

    protected $firstHeartBeat = 0;
   
    /**
     * Number of bytes already sent.
     *
     * @var int
     */

    protected $bytesSent = 0;
   
    /**
     * Total sending time in microseconds.
     *
     * @var int
     */

    protected $sendingTime = 0;
   
    /**
     * Current transfer rate in bytes per second.
     *
     * @var int
     */

    protected $currentLimit = 0;
   
    /**
     * Is this the last packet to send?
     *
     * @var bool
     */

    protected $isFinishing = false;
   
    /**
     * @var ThrottleConfig
     */

    protected $config;
   
    /**
     * Create new instance of throttler
     *
     * @param IThrottleConfig $config Configuration object or null to use system defaults
     * @return Throttle
     */

    public function __construct(IThrottleConfig $config = null) {
        if(function_exists('apache_setenv')) {
            // disable gzip HTTP compression so it would not alter the transfer rate
            apache_setenv('no-gzip', '1');
        }
        // disable the script timeout if supported by the server
        if(false === strpos(ini_get('disable_functions'), 'set_time_limit')) {
            // suppress the warnings (in case of the safe_mode)
            @set_time_limit(0);
        }
        if($config) {
            $this->config = $config;
        } else {
            $this->config = new ThrottleConfig();
        }
       
        // set the burst rate by default as the current transfer rate
        $this->currentLimit = $this->config->burstLimit;
       
        // set the output callback
        ob_start(array($this, 'onFlush'), $this->config->rateLimit);
    }
   
    /**
     * Throttler destructor
     *
     * @return void
     */

    public function __destruct() {
        $this->isFinishing = true;
    }
   
    /**
     * Throttling mechanism
     *
     * @param string $buffer Input buffer
     * @return string Output buffer (the same as input)
     */

    public function onFlush(&amp; $buffer) {
        // do nothing when buffer is empty (in case of implicit ob_flush() or script halt)
        // and check if this is a last portion of the output, if it is - do not throttle
        if($buffer === "" || $this->isFinishing) {
            return $buffer;
        }
               
        // cache the buffer length for futher use
        $bufferLength = strlen($buffer);
       
        // cache current microtime to save us from executing too many system request
        $now = microtime(true);
       
        // initialize last heartbeat time if this is a first iteration of the callback
        if($this->lastHeartBeat === 0) {
            $this->lastHeartBeat = $this->firstHeartBeat = $now;
        }
       
        // calculate how much data have we have to send to the user, so we can set the appropriate time delay
        // if the buffer is smaller than the current limit (per second) send it proportionally faster than the full
        // data package
        $usleep = $bufferLength / $this->currentLimit;
        if($usleep > 0) {
            usleep($usleep * 1000000);
            $this->sendingTime += $usleep;
        }

        // check if the burst rate is active, and if we should switch it off (in both if cases)
        if($this->currentLimit === $this->config->burstLimit &amp;&amp; $this->config->burstLimit !== $this->config->rateLimit) {
            if(isset($this->config->burstSize)) {
                if($this->config->burstSize < $this->bytesSent + $bufferLength) {
                    $this->currentLimit = $this->config->rateLimit;
                }            
            } else {
                if($now > ($this->firstHeartBeat + $this->config->burstTimeout)) {
                    $this->currentLimit = $this->config->rateLimit;
                }
            }
        }
       
        // update system statistics        
        $this->bytesSent += $bufferLength;
        $this->lastHeartBeat = $now;
       
        return $buffer;
    }
   
    /**
     * Returns throttle statistics.
     *
     * @return stdClass
     */

    public function getStatistics() {
        if(ob_get_level() > 0) {
            ob_flush();
        }
        $stats = new stdClass();
        $stats->bytesSent = $this->bytesSent;
        $stats->sendingTime = $this->sendingTime;
        $stats->averageRate = $this->sendingTime > 0 ? $this->bytesSent/$this->sendingTime : $stats->bytesSent;
        return $stats;
    }
}

Scripts for Zebra_Session Page Headers

This PHP Script is a wrapper for PHP’s default session handling functions using MySQL for storage, which provides both better security and better performance. It is also a PHP HTTP solution for applications that are scaled across multiple web services and where the user’s session data needs to be available.

Fixed a small bug in the destroy method; thanks to Tagir Valeev for reporting;
- The script would trigger a PHP notice if the HTTP_USER_AGENT value was not available in the $_SERVER super-global;
- Added a new method “get_settings” that returns the default session-related settings for the environment where the class is used.

 

 

<?php

/**
 *  A PHP class that acts as a wrapper for PHP's default session handling functions but instead of storing session data
 *  in flat files it stores them in a MySQL database, thus providing both better security and better performance.
 *
 *  The class also implements <i>session locking</i>. Session locking is a way to ensure that data is correctly handled
 *  in a scenario with multiple concurrent AJAX requests. Read more about it in this excellent article by <b>Andy Bakun</b>
 *  called {@link http://thwartedefforts.org/2006/11/11/race-conditions-with-ajax-and-php-sessions/ Race Conditions with Ajax and PHP Sessions}.
 *
 *  The Zebra_Session class is also a solution for applications that are scaled across multiple web servers (using a
 *  load balancer or a round-robin DNS) and where the user's session data needs to be available. Storing sessions in a
 *  database makes them available to all of the servers!
 *
 *  This class is was inspired by John Herren's code from the {@link http://devzone.zend.com/node/view/id/141 Trick out
 *  your session handler} article and Chris Shiflett's code from his book {@link http://phpsecurity.org/code/ch08-2
 *  Essential PHP Security} chapter 8, Shared Hosting, Pg. 78-80.
 *
 *  The code is heavily commented and generates no warnings/errors/notices when PHP's error reporting level is set to
 *  E_ALL.
 *
 *  Visit {@link http://stefangabos.ro/php-libraries/zebra-session/} for more information.
 *
 *  For more resources visit {@link http://stefangabos.ro/}
 *
 *  @author     Stefan Gabos <contact@stefangabos.ro>
 *  @version    2.0 (last revision: April 18, 2011)
 *  @copyright  (c) 2006 - 2011 Stefan Gabos
 *  @license    http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE
 *  @package    Zebra_Session
 */


class Zebra_Session
{

 /**
 *  Constructor of class. Initializes the class and automatically calls
 *  {@link http://php.net/manual/en/function.session-start.php start_session()}.
 *
 *  <code>
 *  //  include the class
 *  require 'path/to/Zebra_Session.php';
 *
 *  //  start the session
 *  $session = new Zebra_Session();
 *  </code>
 *
 *  @param  integer     $session_lifetime   (Optional) The number of seconds after which a session will be considered
 *                                          as <i>expired</i>.
 *
 *                                          Expired sessions are cleaned up from the database whenever the <i>garbage
 *                                          collection routine</i> is run. The probability of the <i>garbage collection
 *                                          routine</i> to be executed is given by the values of <i>$gc_probability</i>
 *                                          and <i>$gc_divisor</i>. See below.
 *
 *                                          Default is the value of <i>session.gc_maxlifetime</i> as set in in php.ini.
 *                                          Read more at {@link http://www.php.net/manual/en/session.configuration.php}
 *
 *                                          To clear any confusions that may arise: in reality, <i>session.gc_maxlifetime</i>
 *                                          does not represent a session's lifetime but the number of seconds after
 *                                          which a session is seen as <i>garbage</i> and is deleted by the <i>garbage
 *                                          collection routine</i>. The PHP setting that sets a session's lifetime is
 *                                          <i>session.cookie_lifetime</i> and is usually set to "0" - indicating that
 *                                          a session is active until the browser/browser tab is closed. When this class
 *                                          is used, a session is active until the browser/browser tab is closed and/or
 *                                          a session has been inactive for more than the number of seconds specified
 *                                          by <i>session.gc_maxlifetime</i>.
 *
 *                                          To see the actual value of <i>session.gc_maxlifetime</i> for your
 *                                          environment, use the {@link get_settings()} method.
 *
 *  @param  integer     $gc_probability     (Optional) Used in conjunction with <i>$gc_divisor</i>. It defines the
 *                                          probability that the <i>garbage collection routine</i> is started.
 *
 *                                          The probability is expressed by the formula:
 *
 *                                          <code>
 *                                          $probability = $gc_probability / $gc_divisor;
 *                                          </code>
 *
 *                                          So, if <i>$gc_probability</i> is 1 and <i>$gc_divisor</i> is 100, it means
 *                                          that there is a 1% chance the the <i>garbage collection routine</i> will
 *                                          be called on each request.
 *
 *                                          Default is the value of <i>session.gc_probability</i> as set in php.ini.
 *                                          Read more at {@link http://www.php.net/manual/en/session.configuration.php}
 *
 *                                          To see the actual value of <i>session.gc_probability</i> for your
 *                                          environment, and the computed <i>probability</i>, use the
 *                                          {@link get_settings()} method.
 *
 *  @param  integer     $gc_divisor         (Optional) Used in conjunction with <i>$gc_probability</i>. It defines the
 *                                          probability that the <i>garbage collection routine</i> is started.
 *
 *                                          The probability is expressed by the formula:
 *
 *                                          <code>
 *                                          $probability = $gc_probability / $gc_divisor;
 *                                          </code>
 *
 *                                          So, if <i>$gc_probability</i> is 1 and <i>$gc_divisor</i> is 100, it means
 *                                          that there is a 1% chance the the <i>garbage collection routine</i> will
 *                                          be called on each request.
 *
 *                                          Default is the value of <i>session.gc_divisor</i> as set in php.ini.
 *                                          Read more at {@link http://www.php.net/manual/en/session.configuration.php}
 *
 *                                          To see the actual value of <i>session.gc_divisor</i> for your
 *                                          environment, and the computed <i>probability</i>, use the
 *                                          {@link get_settings()} method.
 *
 *  @param  string      $security_code      (Optional) The value of this argument is appended to the HTTP_USER_AGENT
 *                                          string before creating an MD5 hash out of it and storing it in the database.
 *                                          This way we'll try to prevent HTTP_USER_AGENT spoofing.
 *
 *                                          <i>Make sure you change this code to something else!</i>
 *
 *                                          Default is <i>sEcUr1tY_c0dE</i>
 *
 *  @param  string      $table_name         (Optional) Name of the MySQL table used by the class.
 *
 *                                          Default is <i>session_data</i>.
 *
 *  @param  string      $lock_timeout       (Optional) The maximum amount of time (in seconds) for which a lock on
 *                                          the session data can be kept.
 *
 *                                          <i>This must be lower than the maximum execution time of the script!</i>
 *
 *                                          Session locking is a way to ensure that data is correctly handled in a
 *                                          scenario with multiple concurrent AJAX requests.
 *
 *                                          Read more about it at
 *                                          {@link http://thwartedefforts.org/2006/11/11/race-conditions-with-ajax-and-php-sessions/}
 *
 *                                          Default is <i>60</i>
 *
 *  @return void
 */

 function Zebra_Session($session_lifetime = '', $gc_probability = '', $gc_divisor = '', $security_code = 'sEcUr1tY_c0dE', $table_name = 'session_data', $lock_timeout = 60)
 {

 // continue if there is an active MySQL connection
 if (@mysql_ping()) {

 // make sure session cookies never expire so that session lifetime
 // will depend only on the value of $session_lifetime
 ini_set('session.cookie_lifetime', 0);

 // if $session_lifetime is specified and is an integer number
 if ($session_lifetime != '' &amp;&amp; is_integer($session_lifetime)) {

 // set the new value
 ini_set('session.gc_maxlifetime', $session_lifetime);

 }

 // if $gc_probability is specified and is an integer number
 if ($gc_probability != '' &amp;&amp; is_integer($gc_probability)) {

 // set the new value
 ini_set('session.gc_probability', $gc_probability);

 }

 // if $gc_divisor is specified and is an integer number
 if ($gc_divisor != '' &amp;&amp; is_integer($gc_divisor)) {

 // set the new value
 ini_set('session.gc_divisor', $gc_divisor);

 }

 // get session lifetime
 $this->session_lifetime = ini_get('session.gc_maxlifetime');

 // we'll use this later on in order to try to prevent HTTP_USER_AGENT spoofing
 $this->security_code = $security_code;

 // the table to be used by the class
 $this->table_name = $table_name;

 // the maximum amount of time (in seconds) for which a process can lock the session
 $this->lock_timeout = $lock_timeout;

 // register the new handler
 session_set_save_handler(
 array(&amp;$this, 'open'),
 array(&amp;$this, 'close'),
 array(&amp;$this, 'read'),
 array(&amp;$this, 'write'),
 array(&amp;$this, 'destroy'),
 array(&amp;$this, 'gc')
 );

 // start the session
 session_start();

 // if no MySQL connections could be found
 } else {

 // trigger a fatal error message and stop execution
 trigger_error('<br>No MySQL connection!<br>Error', E_USER_ERROR);

 }

 }

 /**
 *  Custom close() function
 *
 *  @access private
 */

 function close()
 {

 // release the lock associated with the current session
 mysql_query('SELECT RELEASE_LOCK("' . $this->session_lock . '")')

 // stop execution and print message on error
 or die(mysql_error());

 return true;

 }

 /**
 *  Custom destroy() function
 *
 *  @access private
 */

 function destroy($session_id)
 {

 // deletes the current session id from the database
 $result = mysql_query('

 DELETE FROM
 '
. $this->table_name . '
 WHERE
 session_id = "'
. mysql_real_escape_string($session_id) . '"

 '
) or die(mysql_error());

 // if anything happened
 if (mysql_affected_rows() !== -1) {

 // return true
 return true;

 }

 // if something went wrong, return false
 return false;

 }

 /**
 *  Custom gc() function (garbage collector)
 *
 *  @access private
 */

 function gc($maxlifetime)
 {

 // it deletes expired sessions from database
 $result = mysql_query('

 DELETE FROM
 '
. $this->table_name . '
 WHERE
 session_expire < "'
. mysql_real_escape_string(time() - $maxlifetime) . '"

 '
) or die(mysql_error());

 }

 /**
 *  Get the number of active sessions - sessions that have not expired.
 *
 *  <i>The returned value does not represent the exact number of active users as some sessions may be unused
 *  although they haven't expired.</i>
 *
 *  <code>
 *  //  include the class
 *  require 'path/to/Zebra_Session.php';
 *
 *  //  start the session
 *  $session = new Zebra_Session();
 *
 *  //  get the (approximate) number of active sessions
 *  $active_sessions = $session->get_active_sessions();
 *  </code>
 *
 *  @return integer     Returns the number of active (not expired) sessions.
 */

 function get_active_sessions()
 {

 // call the garbage collector
 $this->gc($this->session_lifetime);

 // counts the rows from the database
 $result = @mysql_fetch_assoc(mysql_query('

 SELECT
 COUNT(session_id) as count
 FROM '
. $this->table_name . '

 '
) or die(mysql_error()));

 // return the number of found rows
 return $result['count'];

 }

 /**
 *  Queries the system for the values of <i>session.gc_maxlifetime</i>, <i>session.gc_probability</i> and <i>session.gc_divisor</i>
 *  and returns them as an associative array.
 *
 *  To view the result in a human-readable format use:
 *  <code>
 *  //  include the class
 *  require 'path/to/Zebra_Session.php';
 *
 *  //  instantiate the class
 *  $session = new Zebra_Session();
 *
 *  //  get default settings
 *  print_r('<pre>');
 *  print_r($session->get_settings());
 *
 *  //  would output something similar to (depending on your actual settings)
 *  //  Array
 *  //  (
 *  //      [session.gc_maxlifetime] => 1440 seconds (24 minutes)
 *  //      [session.gc_probability] => 1
 *  //      [session.gc_divisor] => 1000
 *  //      [probability] => 0.1%
 *  //  )
 *  </code>
 *
 *  @since 1.0.8
 *
 *  @return array   Returns the values of <i>session.gc_maxlifetime</i>, <i>session.gc_probability</i> and <i>session.gc_divisor</i>
 *                  as an associative array.
 *
 */

 function get_settings()
 {

 // get the settings
 $gc_maxlifetime = ini_get('session.gc_maxlifetime');
 $gc_probability = ini_get('session.gc_probability');
 $gc_divisor     = ini_get('session.gc_divisor');

 // return them as an array
 return array(
 'session.gc_maxlifetime'    =>  $gc_maxlifetime . ' seconds (' . round($gc_maxlifetime / 60) . ' minutes)',
 'session.gc_probability'    =>  $gc_probability,
 'session.gc_divisor'        =>  $gc_divisor,
 'probability'               =>  $gc_probability / $gc_divisor * 100 . '%',
 );

 }

 /**
 *  Custom open() function
 *
 *  @access private
 */

 function open($save_path, $session_name)
 {

 return true;

 }

 /**
 *  Custom read() function
 *
 *  @access private
 */

 function read($session_id)
 {

 // get the lock name, associated with the current session
 $this->session_lock = mysql_real_escape_string('session_' . $session_id);

 // try to obtain a lock with the given name and timeout
 $result = mysql_query('SELECT GET_LOCK("' . $this->session_lock . '", ' . mysql_real_escape_string($this->lock_timeout) . ')');

 // if there was an error
 if (!is_resource($result) || @mysql_num_rows($result) != 1) {

 // stop execution
 die('Could not obtain session lock!');

 }

 //  reads session data associated with a session id, but only if
 //  -   the session ID exists;
 //  -   the session has not expired;
 //  -   the HTTP_USER_AGENT is the same as the one who had previously been associated with this particular session;
 $result = mysql_query('

 SELECT
 session_data
 FROM
 '
. $this->table_name . '
 WHERE
 session_id = "'
. mysql_real_escape_string($session_id) . '" AND
 session_expire > "'
. time() . '" AND
 http_user_agent = "'
. mysql_real_escape_string(md5((isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '') . $this->security_code)) . '"
 LIMIT 1

 '
) or die(mysql_error());

 // if anything was found
 if (is_resource($result) &amp;&amp; @mysql_num_rows($result) > 0) {

 // return found data
 $fields = @mysql_fetch_assoc($result);

 // don't bother with the unserialization - PHP handles this automatically
 return $fields['session_data'];

 }

 // on error return an empty string - this HAS to be an empty string
 return '';

 }

 /**
 *  Regenerates the session id.
 *
 *  <b>Call this method whenever you do a privilege change in order to prevent session hijacking!</b>
 *
 *  <code>
 *  //  include the class
 *  require 'path/to/Zebra_Session.php';
 *
 *  //  start the session
 *  $session = new Zebra_Session();
 *
 *  //  regenerate the session's ID
 *  $session->regenerate_id();
 *  </code>
 *
 *  @return void
 */

 function regenerate_id()
 {

 // saves the old session's id
 $old_session_id = session_id();

 // regenerates the id
 // this function will create a new session, with a new id and containing the data from the old session
 // but will not delete the old session
 session_regenerate_id();

 // because the session_regenerate_id() function does not delete the old session,
 // we have to delete it manually
 $this->destroy($old_session_id);

 }

 /**
 *  Deletes all data related to the session
 *
 *  <code>
 *  //  include the class
 *  require 'path/to/Zebra_Session.php';
 *
 *  //  start the session
 *  $session = new Zebra_Session();
 *
 *  //  end current session
 *  $session->stop();
 *  </code>
 *
 *  @since 1.0.1
 *
 *  @return void
 */

 function stop()
 {

 $this->regenerate_id();

 session_unset();

 session_destroy();

 }

 /**
 *  Custom write() function
 *
 *  @access private
 */

 function write($session_id, $session_data)
 {

 // insert OR update session's data - this is how it works:
 // first it tries to insert a new row in the database BUT if session_id is already in the database then just
 // update session_data and session_expire for that specific session_id
 // read more here http://dev.mysql.com/doc/refman/4.1/en/insert-on-duplicate.html
 $result = mysql_query('

 INSERT INTO
 '
. $this->table_name . ' (
 session_id,
 http_user_agent,
 session_data,
 session_expire
 )
 VALUES (
 "'
. mysql_real_escape_string($session_id) . '",
 "'
. mysql_real_escape_string(md5((isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '') . $this->security_code)) . '",
 "'
. mysql_real_escape_string($session_data) . '",
 "'
. mysql_real_escape_string(time() + $this->session_lifetime) . '"
 )
 ON DUPLICATE KEY UPDATE
 session_data = "'
. mysql_real_escape_string($session_data) . '",
 session_expire = "'
. mysql_real_escape_string(time() + $this->session_lifetime) . '"

 '
) or die(mysql_error());

 // if anything happened
 if ($result) {

 // note that after this type of queries, mysql_affected_rows() returns
 // - 1 if the row was inserted
 // - 2 if the row was updated

 // if the row was updated
 if (@mysql_affected_rows() > 1) {

 // return TRUE
 return true;

 // if the row was inserted
 } else {

 // return an empty string
 return '';

 }

 }

 // if something went wrong, return false
 return false;

 }

}
?>

&amp;nbsp;

PHP Scripts for Stream Page Headers

This PHP Script is created to retrieve multiple web pages or other web resources in parallel. It sends multiple HTTP requests to different web servers and receive response data from all servers in parallel. Both regular HTTP and HTTPS requests are supported.

 

<?php
/**
 * HTTP adapter for Stream class
 *
 * do ansyncronously HTTP requests
 *
 * @author Alexander Over <phpclasses@quadrat4.de>
 */

class Stream_HTTP extends Stream
{
 /**
 * @var array $request holds the requests
 */

 protected $request = array();

 /**
 * @var integer $port HTTP Port, default 80
 */

 protected $port = 80;

 /**
 * Class constructor
 *
 * set protocol and default socket timeout
 */

 public function __construct()
 {
 $this->protocol = 'tcp';
 $this->timeout = 10;
 $this->request = array();
 }

 /**
 * add a GET request to the request array
 *
 * @param string $host
 * @param string $filename
 * @param array $data
 *
 * @return int $index
 */

 public function addGetRequest($host, $filename = '', $index = null, $function = false, $headers = null)
 {
 $index = ((!is_null($index)) ? $index : count($this->request));
 $this->request[$index]['path'] = $host.':'.$this->port;
 $this->request[$index]['file'] = $filename;
 if ( $function )
 {
 $this->request[$index]['cust'] = $function;
 }
 $this->request[$index]['data'] = "GET ".$filename." HTTP/1.1\r\n".
 "Host: ".$host."\r\n".
 "User-Agent: ".((array_key_exists('HTTP_USER_AGENT', $_SERVER)?$_SERVER['HTTP_USER_AGENT']:'Mozilla compatible') )."\r\n".
 "Accept: text/html,application/xhtml+xml,application/xml;application/json;image/png,image/*;q=0.8,*/*;q=0.5\r\n".
 "Accept-Language: q=0.9,*/*;q=0.8\r\n".
 "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
 $this->request[$index]['data'].= ((is_array($headers)) ? implode("\r\n", $headers)."\r\n" : '').
 "Connection: close\r\n".
 "\r\n";
 return $index;
 }

 /**
 * add a POST request to the request array
 *
 * @param string $host
 * @param string $filename
 * @param array $data
 *
 * @return int $index
 */

 public function addPostRequest($host, $filename = '', $index = null, $postdata, $function = false, $headers = null)
 {
 $poststring = ((is_array($postdata))?http_build_query($postdata):$postdata);
 $index = ((!is_null($index)) ? $index : count($this->request));
 $this->request[$index]['path'] = $host.':'.$this->port;
 $this->request[$index]['file'] = $filename;
 if ( $function )
 {
 $this->request[$index]['cust'] = $function;
 }
 $this->request[$index]['data'] = "POST ".$filename." HTTP/1.0\r\n".
 "Host: ".$host."\r\n".
 "User-Agent: ".((array_key_exists('HTTP_USER_AGENT', $_SERVER)?$_SERVER['HTTP_USER_AGENT']:'Mozilla compatible') )."\r\n".
 "Accept: text/html,application/xhtml+xml,application/xml;application/json;image/png,image/*;q=0.8,*/*;q=0.5\r\n".
 "Accept-Language: q=0.9,*/*;q=0.8\r\n".
 "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
 $this->request[$index]['data'].= "Content-Type: application/x-www-form-urlencoded"."\r\n".
 "Content-Length: ".strlen( $poststring )."\r\n".
 ((is_array($headers)) ? implode("\r\n", $headers)."\r\n" : '').
 "Connection: close\r\n".
 "\r\n".
 $poststring;
 return $index;
 }

 /**
 * send the request
 * @param int $maxParallel limit the count of parallel requests. 0 for no limitation
 *
 * @return array mixed
 */

 public function doRequest($maxParallel = 0)
 {
 $return = parent::doRequest($maxParallel);

 // Split response into header and data
 if (is_array($return) &amp;&amp; count($return))
 {
 foreach ($return as $key => $data)
 {
 $split = explode("\r\n\r\n", $data);
 if (count($split) > 1)
 {
 $readheaders = explode("\r\n", $split[0]);
 foreach ($readheaders as $header)
 {
 $hsplit = explode(':', $header);
 $name = $hsplit[0];
 array_shift($hsplit);
 $headers[$key][$name] = trim(implode(':', $hsplit));
 }
 array_shift($split);
 }
 else
 {
 $headers = array();
 }

 $implode = implode("\r\n\r\n", $split);
 if (is_array($headers[$key]) and (array_key_exists('Transfer-Encoding', $headers[$key]) and $headers[$key]['Transfer-Encoding'] == 'chunked') ||
 (array_key_exists('Content-Transfer-Encoding', $headers[$key]) and $headers[$key]['Content-Transfer-Encoding'] == 'chunked'))
 {
 // chunked
 $split = $this->unchunk($implode);
 }
 else
 {
 // plain
 $split = $implode;
 }
 $result[$key] = $split;
 }

 return array('headers' => $headers,
 'result' => $result);
 } else
 {
 return array();
 }
 }

 private function unchunk($result)
 {
 return preg_replace_callback(
 '/(?:(?:\r\n|\n)|^)([0-9A-F]+)(?:\r\n|\n){1,2}(.*?)'.
 '((?:\r\n|\n)(?:[0-9A-F]+(?:\r\n|\n))|$)/si',
 create_function('$matches', 'return hexdec($matches[1]) == strlen($matches[2]) ? $matches[2] : $matches[0];'), $result
 );
 }
}

&amp;nbsp;

PHP-multi-curl cripts for Page Headers

This is a high performance multi-cURL PHP library which can be used to parallel HTTP web service calls.The library is currently used by projects like Twitter-async, Foursquare-async and many more.It allows developers to select responses based on a criteria.It can fire off 10 HTTP calls and retrieve results for a specific one without having to wait for all 10 to be completed.

 

 

<?php
class EpiCurl
{
 const timeout = 3;
 static $inst = null;
 static $singleton = 0;
 private $mc;
 private $msgs;
 private $running;
 private $execStatus;
 private $selectStatus;
 private $sleepIncrement = 1.1;
 private $requests = array();
 private $responses = array();
 private $properties = array();

 function __construct()
 {
 if(self::$singleton == 0)
 {
 throw new Exception('This class cannot be instantiated by the new keyword.  You must instantiate it using: $obj = EpiCurl::getInstance();');
 }

 $this->mc = curl_multi_init();
 $this->properties = array(
 'code'  => CURLINFO_HTTP_CODE,
 'time'  => CURLINFO_TOTAL_TIME,
 'length'=> CURLINFO_CONTENT_LENGTH_DOWNLOAD,
 'type'  => CURLINFO_CONTENT_TYPE,
 'url'   => CURLINFO_EFFECTIVE_URL
 );
 }

 public function addCurl($ch)
 {
 $key = $this->getKey($ch);
 $this->requests[$key] = $ch;
 curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'headerCallback'));

 $code = curl_multi_add_handle($this->mc, $ch);

 // (1)
 if($code === CURLM_OK || $code === CURLM_CALL_MULTI_PERFORM)
 {
 do {
 $code = $this->execStatus = curl_multi_exec($this->mc, $this->running);
 } while ($this->execStatus === CURLM_CALL_MULTI_PERFORM);

 return new EpiCurlManager($key);
 }
 else
 {
 return $code;
 }
 }

 public function getResult($key = null)
 {
 if($key != null)
 {
 if(isset($this->responses[$key]))
 {
 return $this->responses[$key];
 }

 $innerSleepInt = $outerSleepInt = 1;
 while($this->running &amp;&amp; ($this->execStatus == CURLM_OK || $this->execStatus == CURLM_CALL_MULTI_PERFORM))
 {
 usleep($outerSleepInt);
 $outerSleepInt *= $this->sleepIncrement;
 $ms=curl_multi_select($this->mc, 0);
 if($ms > 0)
 {
 do{
 $this->execStatus = curl_multi_exec($this->mc, $this->running);
 usleep($innerSleepInt);
 $innerSleepInt *= $this->sleepIncrement;
 }while($this->execStatus==CURLM_CALL_MULTI_PERFORM);
 $innerSleepInt = 1;
 }
 $this->storeResponses();
 if(isset($this->responses[$key]['data']))
 {
 return $this->responses[$key];
 }
 $runningCurrent = $this->running;
 }
 return null;
 }
 return false;
 }

 public function cleanupResponses()
 {
 $this->responses = array();
 }

 private function getKey($ch)
 {
 return (string)$ch;
 }

 private function headerCallback($ch, $header)
 {
 $_header = trim($header);
 $colonPos= strpos($_header, ':');
 if($colonPos > 0)
 {
 $key = substr($_header, 0, $colonPos);
 $val = preg_replace('/^\W+/','',substr($_header, $colonPos));
 $this->responses[$this->getKey($ch)]['headers'][$key] = $val;
 }
 return strlen($header);
 }

 private function storeResponses()
 {
 while($done = curl_multi_info_read($this->mc))
 {
 $key = (string)$done['handle'];
 $this->responses[$key]['data'] = curl_multi_getcontent($done['handle']);
 foreach($this->properties as $name => $const)
 {
 $this->responses[$key][$name] = curl_getinfo($done['handle'], $const);
 }
 curl_multi_remove_handle($this->mc, $done['handle']);
 curl_close($done['handle']);
 }
 }

 static function getInstance()
 {
 if(self::$inst == null)
 {
 self::$singleton = 1;
 self::$inst = new EpiCurl();
 }

 return self::$inst;
 }
}

class EpiCurlManager
{
 private $key;
 private $epiCurl;

 function __construct($key)
 {
 $this->key = $key;
 $this->epiCurl = EpiCurl::getInstance();
 }

 function __get($name)
 {
 $responses = $this->epiCurl->getResult($this->key);
 return $responses[$name];
 }

 function __isset($name)
 {
 $val = self::__get($name);
 return empty($val);
 }
}

/*
 * Credits:
 *  - (1) Alistair pointed out that curl_multi_add_handle can return CURLM_CALL_MULTI_PERFORM on success.
 */


&amp;nbsp;

Proof Loaded Files Scripts Page Headers

Proof Loaded Files is a PHP script can track and verify if pages files were loaded. It can generate URLs that for links and other page elemements for serving files dynamically.The script can keep track of linked and downloaded files using session variables, so it can verify if the user browser has really loaded the linked files.

 

 

<?php
/*******************************************
 * Author: Max Nowack                      *
 * Website: www.dasnov.de                  *
 * Classname: ProofLoadedFiles             *
 *******************************************
 * Description:                            *
 * The class proof which files are loaded  *
 * from the client. With this class your   *
 * can make forms or sites securer.        *
 * Example:                                *
 * The client must load all external files *
 * they liked in the script (stylesheets,  *
 * images, etc.). Otherwise the next site  *
 * will not open.                          *
 *******************************************/


session_start();    //Start the Session. If you also use sessions on your script, comment this line out.


define("SESSION_VAR_PREFIX",    "ProofLoadedFiles_");

class ProofLoadedFiles
{
 var $linkTo;        //link to the file that open the other files (images, stylesheets, etc.)
 var $pathTo;        //path to the other files (images, stylesheets, etc.)
 var $loadedFiles;    //array that contains the files opened by the script
 var $showedLinks;    //array that contains the files showed by the script
 var $numSitesInSession;    //number of the runtimes of the class in this session

 function __construct($linkTo,$pathTo)
 {
 //make the sessionvars local
 $this->loadedFiles = $this->getSessionVar("loadedFiles",array());
 $this->showedLinks = $this->getSessionVar("showedLinks",array());
 $this->numSitesInSession = $this->getSessionVar("numSitesInSession",0);

 //save the classparameters
 $this->linkTo = $linkTo;
 $this->pathTo = $pathTo;

 $this->numSitesInSession++;    //increase session site number
 }

 function __destruct()
 {
 //save the localvars into sessionvars
 $this->setSessionVar("loadedFiles",$this->loadedFiles);
 $this->setSessionVar("showedLinks",$this->showedLinks);
 $this->setSessionVar("numSitesInSession",$this->numSitesInSession);
 }

 function showLinkTo($file)
 {
 //this function returns the link to the file $file
 $this->showedLinks[$this->numSitesInSession][] = $file;
 if(strstr($this->linkTo,"?"))
 {
 return $this->linkTo.$file."&amp;x=".time();
 }
 else
 {
 return $this->linkTo.$file."?x=".time();
 }
 }

 function getMimeType($file)
 {
 //this function returns the mimetype of the file $file
 if(function_exists(finfo_open))    //tests finfo installation
 {
 $finfo = finfo_open(FILEINFO_MIME_TYPE);    // return mime type ala mimetype extension
 return finfo_file($finfo,$this->pathTo.$file);
 }
 else    //use the old function
 {
 return mime_content_type($this->pathTo.$file);
 }
 }

 function load($file)
 {
 //this function returns the content of the file $file
 //if the link to the file was never shown in this session or , the function will return false
 $this->numSitesInSession--;    //decrease session site number
 if($this->canLoadFile($file) &amp;&amp; file_exists($this->pathTo.$file))
 {
 $this->loadedFiles[$this->numSitesInSession][] = $file; //add the file to the loadedFiles-Array
 return file_get_contents($this->pathTo.$file); // return the file content
 }
 else
 {
 return false;
 }
 }

 function proof()
 {
 //this function proof the loaded files. If all files are loaded,
 //the function will return true. Otherwise the function return false
 if($this->numSitesInSession>1) //start just in sessions > 1
 {

 $lastSession = $this->numSitesInSession - 1; //get the last session

 //proof showed links and loaded files > 0
 if(count($this->loadedFiles[$lastSession])>0 &amp;&amp; count($this->showedLinks[$lastSession])>0)
 {
 //sort the arrays
 sort($this->loadedFiles[$lastSession]);
 sort($this->showedLinks[$lastSession]);

 if($this->loadedFiles[$lastSession]==$this->showedLinks[$lastSession])
 {
 return true;
 }
 else
 {
 return false;
 }
 }
 elseif(count($this->loadedFiles[$lastSession])>0 xor count($this->showedLinks[$lastSession])>0)
 {
 return false;
 }
 else
 {
 return true;
 }

 }
 else
 {
 return true;
 }
 }

 function canLoadFile($file)
 {//this function return true if the file was allready shown
 $arr_str = json_encode($this->showedLinks);
 if(strstr($arr_str,$file))
 {
 return true;
 }
 else
 {
 return false;
 }
 }

 function getSessionVar($var,$init)
 {
 if(!isset($_SESSION[SESSION_VAR_PREFIX.$var]))
 {
 $this->setSessionVar($var,$init);
 }

 return $_SESSION[SESSION_VAR_PREFIX.$var];
 }

 function setSessionVar($var,$val)
 {
 $_SESSION[SESSION_VAR_PREFIX.$var] = $val;
 }
}
?>

&amp;nbsp;

Scripts for Saff Request Page Headers

This script can retrieve the current HTTP request variables. It can retrieve the values of HTTP POST, GET, FILES and REQUEST variables. The script also can filter request variables all at once and return an array of request variables that match a given regular expression.

 

 

<?php
/*
 * Copyright (c) SAFAROFF Creative Agency
 * Coded: Agshin Y. Khaligov &amp; Ismayilzadeh Zulfugar
 */


class Request {

 function __construct(){
 //This is construct of class
 }

 function __destruct(){
 //This is destruct of class
 }

 function __get($name){

 $ret_val = false;

 $splitted_name = preg_split('/__/', $name);

 if(count($splitted_name)>1){

 $request_type = $splitted_name[0];
 $variable = $splitted_name[1];

 switch($request_type){
 case 'POST':{

 if(isset($_POST[$variable])){
 if(!empty($_POST[$variable]))
 $ret_val = $_POST[$variable];
 }

 break;
 }
 case 'GET':{

 if(isset($_GET[$variable])){
 if(!empty($_GET[$variable]))
 $ret_val = $_GET[$variable];
 }

 break;
 }
 case 'FILES':{

 if(isset($_FILES[$variable])){
 if(!empty($_FILES[$variable])){
 $ret_val = $_FILES[$variable];
 }
 }

 break;
 }


 }
 }
 else{

 if(isset($_POST[$name])){
 if(!empty($_POST[$name])){
 $ret_val = $_POST[$name];
 }
 }
 elseif(isset($_GET[$name])){
 if(!empty($_GET[$name])){
 $ret_val = $_GET[$name];
 }
 }
 elseif(isset($_FILES[$variable])){
 if(!empty($_FILES[$variable])){
 $ret_val = $_FILES[$variable];
 }
 }

 }

 return $this->filter($ret_val);
 }

 function __call($method, $args){
 // This function is for filtering request array with regular expression.
 switch($method){

 CASE 'POST':{

 if(isset($_POST)){
 if(!empty($_POST)){
 $ret_array = array();
 foreach($_POST as $index=>$val){
 if(preg_match($args[0], $index)){
 $ret_array[$index] = $val;
 }
 }

 }
 }

 break;
 }

 CASE 'GET':{

 if(isset($_GET)){
 if(!empty($_GET)){
 $ret_array = array();
 foreach($_GET as $index=>$val){
 if(preg_match($args[0], $index)){
 $ret_array[$index] = $val;
 }
 }
 }
 }

 break;
 }

 CASE 'REQUEST':{
 // Find the request type
 if(isset($_POST)){
 if(!empty($_POST)){
 $ret_array = $this->POST($args[0]);
 }
 }
 elseif(isset($_GET)){
 if(!empty($_GET)){
 $ret_array = $this->GET($args[0]);
 }
 }

 break;
 }

 }

 return $ret_array;
 }

 function filter($data){

 /*
 * TODO: Find the best way of filtering data
 */

 if(is_array($data)){
 foreach($data as $key=>$val)
 $data[$key] = $this->filter($val);
 }
 else{
 $data = trim($data);

 if(get_magic_quotes_gpc()){
 $data = stripslashes($data);
 }

 $data = mysql_real_escape_string($data);
 }

 return $data;
 }

}

?>

&amp;nbsp;

Free Contact Form php Page Headers

Free Contact Form will fectch you more details of your ecternal clients and you network of business will improve a lot. All product related enquiries can be solved online and it will be an ideal mode of providing a better service to your clients. Keeping all in our mind, we have generated a script with which the contact form can be installed easily in your website. Just copy the files into server and then give the link. And now, you will start receiving mails in your mail box.

 

 

<?
session_start();
$cansend=$HTTP_POST_VARS['cansend'];
if($cansend==1) {
require 'contact_setting.inc';
$mailTo = "$mailto";

$mailSubject="From ".$HTTP_POST_VARS["txtname"];
$name=$HTTP_POST_VARS["txtname"];
$company=$HTTP_POST_VARS["txtcompany"];
$address=$HTTP_POST_VARS["txtaddress"];
$phone=$HTTP_POST_VARS["txtphone"];
$fax=$HTTP_POST_VARS["txtfax"];
$email=$HTTP_POST_VARS["txtemail"];
$url=$HTTP_POST_VARS["txturl"];
$purpose=$HTTP_POST_VARS["txtpurpose"];
$comment=$HTTP_POST_VARS["txtcomment"];

$mailbody="Name :".$name;
$mailbody=$mailbody."\n Company :".$company;
$mailbody=$mailbody."\n Address :".$address;
$mailbody=$mailbody."\nPhone: ".$phone;
$mailbody=$mailbody."\nFax :".$fax;
$mailbody=$mailbody."\nEmail :".$email;
$mailbody=$mailbody."\nURL :".$url;
$mailbody=$mailbody."\nPurpose :".$purpose;
$mailbody=$mailbody."\nComments :".$comment;

if(1)
{
$status="<div align='center' class='highlight1' style='width: 750px;'>Thank you for contacting us. We will respond you shortly<br><br></div></center>";
}
else
{
$status="<center><br><br><br><div  class='highlight1'>Problem in sending your request.</div></center>";
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Contact Form</title>
<style type="text/css">
<!--
body {
 margin-left: 0px;
 margin-top: 0px;
 margin-right: 0px;
 margin-bottom: 0px;
}
-->
</style>
<link href="style/contact.css" rel="stylesheet" type="text/css" />
</head>

<body>
<table width="100%" border="0" align="left" cellpadding="0" cellspacing="0" background="images/bg.jpg" style=" border-left:1px solid #7f7f7f; border-right:1px solid #7f7f7f; border-bottom:1px solid #7f7f7f; ">

 <tr>
 <td colspan="10"><img src="images/logo.jpg" width="179" height="80" /></td>
 </tr>

 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td colspan="8">&amp;nbsp;</td>
 </tr>

 <tr>
 <td width="2%" bgcolor="#EDEEFC" style="border-bottom:1px solid #cccccc; border-top:1px solid #cccccc">&amp;nbsp;</td>
 <td width="14%" bgcolor="#EDEEFC" style="border-bottom:1px solid #cccccc;border-top:1px solid #cccccc"><b>Contact Us </b></td>
 <td colspan="8" bgcolor="#EDEEFC" style="border-bottom:1px solid #cccccc;border-top:1px solid #cccccc">&amp;nbsp;</td>
 </tr>
 <?php
 if($status) {
 ?>
 <tr>
 <td colspan="6">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="6"><?php echo $status;?></td>
 </tr>
 <tr>
 <td colspan="6" align="center"><a href="javascript: history.go(-1)">Back</a></td>
 </tr>
 <?php
 }
 else {
 ?>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td colspan="8">&amp;nbsp;</td>
 </tr>
 <form method="post" name=form1 action="contact.php" onSubmit="return validate();">
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td width="23%" valign="top"><span>Name: </span></td>
 <td colspan="7"><input name="txtname" type="text"  style="width:250" maxlength="150" /></td>
 </tr>
 <tr>
 <td colspan="10">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top"><span>Company Name: </span></td>
 <td colspan="7"><input name="txtcompany" type="text"  style="width:250" maxlength="150" /></td>
 </tr>
 <tr>
 <td colspan="10">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top"><span>Address:</span></td>
 <td colspan="7"><input name="txtaddress" type="text"  style="width:250" maxlength="150" /></td>
 </tr>
 <tr>
 <td colspan="10">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top"><span>Phone Number:</span></td>
 <td colspan="7"><input name="txtphone" type="text"  style="width:250" maxlength="150" /></td>
 </tr>
 <tr>
 <td colspan="10">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top"><span>Fax Number: </span></td>
 <td colspan="7"><input name="txtfax" type="text"  style="width:250" maxlength="150" /></td>
 </tr>
 <tr>
 <td colspan="10">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top"><span>E-mail id: </span></td>
 <td colspan="7"><input name="txtemail" type="text"  style="width:250" maxlength="150" /></td>
 </tr>
 <tr>
 <td colspan="10">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top"><span>URL: </span></td>
 <td colspan="7"><input name="txturl" type="text"  style="width:250" maxlength="150" /></td>
 </tr>
 <tr>
 <td colspan="10">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top"><span>Contact Purpose: </span></td>
 <td colspan="7"><input name="txtpurpose" type="text"  style="width:250" maxlength="150" /></td>
 </tr>
 <tr>
 <td colspan="10">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top"><span>Comment ( if any ): </span></td>
 <td colspan="7"><textarea name="txtcomment" cols="25"></textarea></td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top">&amp;nbsp;</td>
 <td colspan="7">&amp;nbsp;</td>
 </tr>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top">&amp;nbsp;</td><input type="hidden" name="cansend" value="0">
 <td width="22%"><input name="submit" type="submit" value = "Submit" /></td>
 <td width="39%" colspan="6"><input name="reset" type="reset" value = "Reset" /></td>
 </tr></form>
 <?php } ?>
 <tr>
 <td colspan="2">&amp;nbsp;</td>
 <td valign="top">&amp;nbsp;</td>
 <td>&amp;nbsp;</td>
 <td colspan="6">&amp;nbsp;</td>
 </tr>
</table>
</body>
</html>
<script language="JavaScript">
function validate()
{
 if(trim(document.form1.txtname.value) == "")
 {
 alert("Please Enter Your Name");
 document.form1.txtname.focus();
 return false;
 }
 if(trim(document.form1.txtcompany.value) == "")
 {
 alert("Please Enter Your Company Name");
 document.form1.txtcompany.focus();
 return false;
 }
 if(trim(document.form1.txtaddress.value) == "")
 {
 alert("Please Enter Your Address");
 document.form1.txtaddress.focus();
 return false;
 }
 phoneno = document.form1.txtphone.value;
 len = phoneno.length;
 if(len > 0)
 {
 for(i=0;i<len;i++)
 {
 x = phoneno.substr(i,1)
 if( !( (x >= '0' &amp;&amp; x <= '9') || x == '-') )
 {
 alert("Please Enter the valid Phone number");
 document.form1.txtphone.focus();
 return false;
 }
 }
 }
 faxno = document.form1.txtfax.value;
 len = faxno.length;
 if(len > 0)
 {
 for(i=0;i<len;i++)
 {
 x = faxno.substr(i,1)
 if( !( (x >= '0' &amp;&amp; x <= '9') || x == '-') )
 {
 alert("Please Enter the valid fax number");
 document.form1.txtfax.focus();
 return false;
 }
 }
 }
 if(trim(document.form1.txtemail.value) == "")
 {
 alert("Please Enter Your Email Id");
 document.form1.txtemail.focus();
 return false;
 }
 if( !isEmail(document.form1.txtemail.value) )
 {
 alert("Please Enter the Valid Email Id");
 document.form1.txtemail.focus();
 document.form1.txtemail.select();
 return false;
 }
 if(trim(document.form1.txtpurpose.value) == "")
 {
 alert("Please Enter the Purpose");
 document.form1.txtpurpose.focus();
 return false;
 }

 document.form1.cansend.value=1;

 return true;
}
function isEmail(emailstr)
{
 dotchar = emailstr.indexOf(".");
 atchar = emailstr.indexOf("@");
 dotlast = emailstr.lastIndexOf(".");
 spacechar = emailstr.indexOf(" ");
 len = emailstr.length;
 if( (dotchar == -1) || (atchar == -1) || (spacechar != -1) || (dotlast < atchar) || (dotlast == len - 1) )
 {
 return false;
 }
 else
 {
 return true;
 }
}
function trim(str)
{
ch = '';
for(i=0;i<str.length;i++)
{
 cha = str.charAt(i);
 if(cha != ' ')
 {
 ch = ch + cha;
 }
}
return ch;
}
</script>

&amp;nbsp;

Fast Secure Contact Form Page Headers

Fast Secure Contact Form is a free Contact Form PHP script which allows a users to easilly created and add contact forms to a web page. The form will let the user send emails to a site’s admin. An adminstration panel is present, where the user can create and preview his forms.- Super easy customizable Options from Admin settings page.- Multi-Form feature that allows you to have as many different forms as you need.- Optional extra fields of any type: text, textarea, checkbox, radio, select, attachment, date, fieldset(box).- File attachments- Backup/restore tool. You can backup/restore all your forms or single forms and settings.- Easy to hide subject and message fields for use as a newsletter signup.- Supports sending mail to multiple departments.

 

 

<?php
/*
Fast Secure Contact Form - PHP Script
Author: Mike Challis
http://www.FastSecureContactForm.com/
*/

//do not allow direct access
if ( strpos(strtolower($_SERVER['SCRIPT_NAME']),strtolower(basename(__FILE__))) ) {
 header('HTTP/1.0 403 Forbidden');
 exit('Forbidden');
}

/**
 * Akismet anti-comment spam service
 *
 * The class in this package allows use of the {@link http://akismet.com Akismet} anti-comment spam service in any PHP5 application.
 *
 * This service performs a number of checks on submitted data and returns whether or not the data is likely to be spam.
 *
 * Please note that in order to use this class, you must have a vaild {@link http://wordpress.com/api-keys/ WordPress API key}.  They are free for non/small-profit types and getting one will only take a couple of minutes.
 *
 * For commercial use, please {@link http://akismet.com/commercial/ visit the Akismet commercial licensing page}.
 *
 * Please be aware that this class is PHP5 only.  Attempts to run it under PHP4 will most likely fail.
 *
 * See the Akismet class documentation page linked to below for usage information.
 *
 * @package        akismet
 * @author        Alex Potsides, {@link http://www.achingbrain.net http://www.achingbrain.net}
 * @version        0.4
 * @copyright    Alex Potsides, {@link http://www.achingbrain.net http://www.achingbrain.net}
 * @license        http://www.opensource.org/licenses/bsd-license.php BSD License
 */


/**
 *    The Akismet PHP5 Class
 *
 *  This class takes the functionality from the Akismet WordPress plugin written by {@link http://photomatt.net/ Matt Mullenweg} and allows it to be integrated into any PHP5 application or website.
 *
 *  The original plugin is {@link http://akismet.com/download/ available on the Akismet website}.
 *
 *  <b>Usage:</b>
 *  <code>
 *    $akismet = new Akismet('http://www.example.com/blog/', 'aoeu1aoue');
 *    $akismet->setCommentAuthor($name);
 *    $akismet->setCommentAuthorEmail($email);
 *    $akismet->setCommentAuthorURL($url);
 *    $akismet->setCommentContent($comment);
 *    $akismet->setPermalink('http://www.example.com/blog/alex/someurl/');
 *    if($akismet->isCommentSpam())
 *      // store the comment but mark it as spam (in case of a mis-diagnosis)
 *    else
 *      // store the comment normally
 *  </code>
 *
 *  Optionally you may wish to check if your WordPress API key is valid as in the example below.
 *
 * <code>
 *   $akismet = new Akismet('http://www.example.com/blog/', 'aoeu1aoue');
 *
 *   if($akismet->isKeyValid()) {
 *     // api key is okay
 *   } else {
 *     // api key is invalid
 *   }
 * </code>
 *
 *    @package    akismet
 *    @name        Akismet
 *    @version    0.4
 *  @author        Alex Potsides
 *  @link        http://www.achingbrain.net/
 */

class Akismet
 {
 private $version = '0.4';
 private $wordPressAPIKey;
 private $blogURL;
 private $comment;
 private $apiPort;
 private $akismetServer;
 private $akismetVersion;

 // This prevents some potentially sensitive information from being sent accross the wire.
 private $ignore = array('HTTP_COOKIE',
 'HTTP_X_FORWARDED_FOR',
 'HTTP_X_FORWARDED_HOST',
 'HTTP_MAX_FORWARDS',
 'HTTP_X_FORWARDED_SERVER',
 'REDIRECT_STATUS',
 'SERVER_PORT',
 'PATH',
 'DOCUMENT_ROOT',
 'SERVER_ADMIN',
 'QUERY_STRING',
 'PHP_SELF' );

 /**
 *    @param    string    $blogURL            The URL of your blog.
 *    @param    string    $wordPressAPIKey    WordPress API key.
 */

 public function __construct($blogURL, $wordPressAPIKey) {
 $this->blogURL = $blogURL;
 $this->wordPressAPIKey = $wordPressAPIKey;

 // Set some default values
 $this->apiPort = 80;
 $this->akismetServer = 'rest.akismet.com';
 $this->akismetVersion = '1.1';

 // Start to populate the comment data
 $this->comment['blog'] = $blogURL;
 $this->comment['user_agent'] = (isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : '';
 $this->comment['referrer'] = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : '';

 /*
 * This is necessary if the server PHP5 is running on has been set up to run PHP4 and
 * PHP5 concurently and is actually running through a separate proxy al a these instructions:
 * http://www.schlitt.info/applications/blog/archives/83_How_to_run_PHP4_and_PHP_5_parallel.html
 * and http://wiki.coggeshall.org/37.html
 * Otherwise the user_ip appears as the IP address of the PHP4 server passing the requests to the
 * PHP5 one...
 */

 $this->comment['user_ip'] = $_SERVER['REMOTE_ADDR'] != getenv('SERVER_ADDR') ? $_SERVER['REMOTE_ADDR'] : getenv('HTTP_X_FORWARDED_FOR');
 }

 /**
 * Makes a request to the Akismet service to see if the API key passed to the constructor is valid.
 *
 * Use this method if you suspect your API key is invalid.
 *
 * @return bool    True is if the key is valid, false if not.
 */

 public function isKeyValid() {
 // Check to see if the key is valid
 $response = $this->sendRequest('key=' . $this->wordPressAPIKey . '&amp;blog=' . $this->blogURL, $this->akismetServer, '/' . $this->akismetVersion . '/verify-key');
 return $response[1] == 'valid';
 }

 // makes a request to the Akismet service
 private function sendRequest($request, $host, $path) {
 $http_request  = "POST " . $path . " HTTP/1.0\r\n";
 $http_request .= "Host: " . $host . "\r\n";
 $http_request .= "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n";
 $http_request .= "Content-Length: " . strlen($request) . "\r\n";
 $http_request .= "User-Agent: Akismet PHP5 Class " . $this->version . " | Akismet/1.11\r\n";
 $http_request .= "\r\n";
 $http_request .= $request;

 $socketWriteRead = new SocketWriteRead($host, $this->apiPort, $http_request);
 $socketWriteRead->send();

 return explode("\r\n\r\n", $socketWriteRead->getResponse(), 2);
 }

 // Formats the data for transmission
 private function getQueryString() {
 $ignore = array( 'HTTP_COOKIE', 'HTTP_COOKIE2', 'PHP_AUTH_PW' );
 foreach($_SERVER as $key => $value) {
 if ( !in_array( $key, $ignore ) &amp;&amp; is_string($value) ) {
 if($key == 'REMOTE_ADDR') {
 $this->comment[$key] = $this->comment['user_ip'];
 } else {
 $this->comment[$key] = $value;
 }
 }
 }

 $query_string = '';

 foreach($this->comment as $key => $data) {
 if(!is_array($data)) {
 $query_string .= $key . '=' . urlencode(stripslashes($data)) . '&amp;';
 }
 }

 return $query_string;
 }

 /**
 *    Tests for spam.
 *
 *    Uses the web service provided by {@link http://www.akismet.com Akismet} to see whether or not the submitted comment is spam.  Returns a boolean value.
 *
 *    @return        bool    True if the comment is spam, false if not
 *  @throws        Will throw an exception if the API key passed to the constructor is invalid.
 */

 public function isCommentSpam() {
 $response = $this->sendRequest($this->getQueryString(), $this->wordPressAPIKey . '.rest.akismet.com', '/' . $this->akismetVersion . '/comment-check');

 if($response[1] == 'invalid' &amp;&amp; !$this->isKeyValid()) {
 throw new exception( _('The API key passed to Akismet is invalid. Please obtain a valid one from http://akismet.com/') );
 }

 return ($response[1] == 'true');
 }

 /**
 *    Submit spam that is incorrectly tagged as ham.
 *
 *    Using this function will make you a good citizen as it helps Akismet to learn from its mistakes.  This will improve the service for everybody.
 */

 public function submitSpam() {
 $this->sendRequest($this->getQueryString(), $this->wordPressAPIKey . '.' . $this->akismetServer, '/' . $this->akismetVersion . '/submit-spam');
 }

 /**
 *    Submit ham that is incorrectly tagged as spam.
 *
 *    Using this function will make you a good citizen as it helps Akismet to learn from its mistakes.  This will improve the service for everybody.
 */

 public function submitHam() {
 $this->sendRequest($this->getQueryString(), $this->wordPressAPIKey . '.' . $this->akismetServer, '/' . $this->akismetVersion . '/submit-ham');
 }

 /**
 *    To override the user IP address when submitting spam/ham later on
 *
 *    @param string $userip    An IP address.  Optional.
 */

 public function setUserIP($userip) {
 $this->comment['user_ip'] = $userip;
 }

 /**
 *    To override the referring page when submitting spam/ham later on
 *
 *    @param string $referrer    The referring page.  Optional.
 */

 public function setReferrer($referrer) {
 $this->comment['referrer'] = $referrer;
 }

 /**
 *    A permanent URL referencing the blog post the comment was submitted to.
 *
 *    @param string $permalink    The URL.  Optional.
 */

 public function setPermalink($permalink) {
 $this->comment['permalink'] = $permalink;
 }

 /**
 *    The type of comment being submitted.
 *
 *    May be blank, comment, trackback, pingback, or a made up value like "registration" or "wiki".
 */

 public function setCommentType($commentType) {
 $this->comment['comment_type'] = $commentType;
 }

 /**
 *    The name that the author submitted with the comment.
 */

 public function setCommentAuthor($commentAuthor) {
 $this->comment['comment_author'] = $commentAuthor;
 }

 /**
 *    The email address that the author submitted with the comment.
 *
 *    The address is assumed to be valid.
 */

 public function setCommentAuthorEmail($authorEmail) {
 $this->comment['comment_author_email'] = $authorEmail;
 }

 /**
 *    The URL that the author submitted with the comment.
 */

 public function setCommentAuthorURL($authorURL) {
 $this->comment['comment_author_url'] = $authorURL;
 }

 /**
 *    The comment's body text.
 */

 public function setCommentContent($commentBody) {
 $this->comment['comment_content'] = $commentBody;
 }

 /**
 *    Defaults to 80
 */

 public function setAPIPort($apiPort) {
 $this->apiPort = $apiPort;
 }

 /**
 *    Defaults to rest.akismet.com
 */

 public function setAkismetServer($akismetServer) {
 $this->akismetServer = $akismetServer;
 }

 /**
 *    Defaults to '1.1'
 */

 public function setAkismetVersion($akismetVersion) {
 $this->akismetVersion = $akismetVersion;
 }
}

/**
 *    Utility class used by Akismet
 *
 *  This class is used by Akismet to do the actual sending and receiving of data.  It opens a connection to a remote host, sends some data and the reads the response and makes it available to the calling program.
 *
 *  The code that makes up this class originates in the Akismet WordPress plugin, which is {@link http://akismet.com/download/ available on the Akismet website}.
 *
 *    N.B. It is not necessary to call this class directly to use the Akismet class.  This is included here mainly out of a sense of completeness.
 *
 *    @package    akismet
 *    @name        SocketWriteRead
 *    @version    0.1
 *  @author        Alex Potsides
 *  @link        http://www.achingbrain.net/
 */

class SocketWriteRead {
 private $host;
 private $port;
 private $request;
 private $response;
 private $responseLength;
 private $errorNumber;
 private $errorString;

 /**
 *    @param    string    $host            The host to send/receive data.
 *    @param    int        $port            The port on the remote host.
 *    @param    string    $request        The data to send.
 *    @param    int        $responseLength    The amount of data to read.  Defaults to 1160 bytes.
 */

 public function __construct($host, $port, $request, $responseLength = 1160) {
 $this->host = $host;
 $this->port = $port;
 $this->request = $request;
 $this->responseLength = $responseLength;
 $this->errorNumber = 0;
 $this->errorString = '';
 }

 /**
 *  Sends the data to the remote host.
 *
 * @throws    An exception is thrown if a connection cannot be made to the remote host.
 */

 public function send() {
 $this->response = '';

 $fs = fsockopen($this->host, $this->port, $this->errorNumber, $this->errorString, 3);

 if($this->errorNumber != 0) {
 throw new Exception( _('Error connecting to Akismet host: ') . $this->host . ' Error number: ' . $this->errorNumber . ' Error message: ' . $this->errorString);
 }

 if($fs !== false) {
 @fwrite($fs, $this->request);

 while(!feof($fs)) {
 $this->response .= fgets($fs, $this->responseLength);
 }

 fclose($fs);
 }
 }

 /**
 *  Returns the server response text
 *
 *  @return    string
 */

 public function getResponse() {
 return $this->response;
 }

 /**
 *    Returns the error number
 *
 *    If there was no error, 0 will be returned.
 *
 *    @return int
 */

 public function getErrorNumner() {
 return $this->errorNumber;
 }

 /**
 *    Returns the error string
 *
 *    If there was no error, an empty string will be returned.
 *
 *    @return string
 */

 public function getErrorString() {
 return $this->errorString;
 }
}

?>

&amp;nbsp;

PHP Scripts for Domain Hunter Headers

Domain Hunter is a simple application to monitor the state of a list of domain names.Changes in the status of a monitored domain can be sent to an email address or the domain information can be obtained on demand through a Web interfac. Only the .com and .net top-level domains are currently supported.

 

 

<?php
/*
 +-----------------------------------------------------------------------+
 | Domain Hunter - A Simple Domain Monitoring Application                |
 | Version 0.1.0                                                         |
 |                                                                       |
 | Copyright (C) 2006-2007, DomainLabs.EU - Turkey                       |
 | Licensed under the GNU GPLv3                                          |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Bahri Meric CANLI <bahri@bahri.info>                          |
 +-----------------------------------------------------------------------+

*/


include("whois_class.php");
include("satir_func.php");
include_once("config.inc.php");

function hunter_islemci($dom) {

Global $servers,$hunter_email;

$target_domain = explode(".", $dom);

$target_domainss = strtoupper($target_domain[0].".".$target_domain[1]);

echo $target_domainss;


 $my_whois = new Whois_domain;
 $my_whois->possible_tlds = array_keys($servers); // this is the array from the included server list
 $my_whois->tld = $target_domain[1];
 $my_whois->domain = $target_domain[0];
 $my_whois->free_string = $servers[ $target_domain[1] ]['free'];
 $my_whois->whois_server = $servers[ $target_domain[1] ]['address'];
 $my_whois->whois_param = $servers[ $target_domain[1] ]['param'];
 $my_whois->full_info = "yes";  // between "no" and "yes" to get all whois information
 $my_whois->process();


 if ($my_whois->info != "") {
 $sonuc = nl2br($my_whois->info);
 echo "    ok\n";
 }
else {
 echo "    error\n";
 $bilgi_kontrol = 1;
 }



$sonuc = str_replace("   ", "", $sonuc);
// $sonuc = str_replace("   ", "<br>", $sonuc);
// $sonuc = str_replace("<br />", "<br>", $sonuc);
ereg('(.*)>>> Last update', $sonuc, $lines);
$temp = explode('<br />',$lines[1]);


$d=1; $j=1;$k = 1;

while($d<count($temp)) {


$kol =  satirbul($temp[$d]);


if ($kol[0] == "Domain Name") { $domain_name = $kol[1]; }
if ($kol[0] == "Registrar") { $registrar = $kol[1]; }
if ($kol[0] == "Whois Server") { $whois_server = $kol[1]; }
if ($kol[0] == "Referral URL") { $referral_url = $kol[1]; }
if ($kol[0] == "Status")  {  $status[$k] = $kol[1];  $k++; }
if ($kol[0] == "Updated Date") { $updated_date = $kol[1]; }
if ($kol[0] == "Creation Date") { $creation_date = $kol[1]; }
if ($kol[0] == "Expiration Date") { $expiration_date = $kol[1]; }
if ($kol[0] == "Name Server")  {  $name_server[$j] = $kol[1];  $j++; }

 $d++;

}


$registrar = str_replace(",", " ", $registrar);
$creation_date  = strftime ("%Y-%m-%d", strtotime($creation_date));
$updated_date = strftime ("%Y-%m-%d", strtotime($updated_date));
$expiration_date = strftime ("%Y-%m-%d", strtotime($expiration_date));


$soru=mysql_query("SELECT count(id) FROM monitors where domain = '$target_domainss' ");
$row = mysql_fetch_assoc($soru);
$varmi = $row['count(id)'];


if ( ($varmi == 0 ) &amp;&amp; ($bilgi_kontrol != 1) ) {


$new_domain = "INSERT INTO monitors (`domain`, `register`, `whois_serv`, `ref_url`, `nameserv1`, `nameserv2`, `nameserv3`, `nameserv4`, `nameserv5`,  `status1`, `status2`, `status3`, `create_date`, `update_date`, `expirate_date`)

VALUES ('$domain_name', '$registrar',  '$whois_server', '$referral_url', '$name_server[1]', '$name_server[2]', '$name_server[3]', '$name_server[4]', '$name_server[5]', '$status[1]', '$status[2]', '$status[3]', '$creation_date', '$updated_date', '$expiration_date')"
;

$soru=mysql_query($new_domain) || die (mysql_error());

}
else if ($varmi != 0 ) {

$creation_date  = strftime ("%Y-%m-%d", strtotime($creation_date));
$updated_date = strftime ("%Y-%m-%d", strtotime($updated_date));
$expiration_date = strftime ("%Y-%m-%d", strtotime($expiration_date));


$b_s = "SELECT * FROM `monitors` WHERE domain = '$target_domainss'";
$b_r =  mysql_query ($b_s) ;
$sattir = mysql_fetch_array($b_r);


$esda_register = $sattir['register'];
$esda_whois_serv = $sattir['whois_serv'];
$esda_ref_url = $sattir['ref_url'];
$esda_nameserv1 = $sattir['nameserv1'];
$esda_nameserv2 = $sattir['nameserv2'];
$esda_nameserv3 = $sattir['nameserv3'];
$esda_nameserv4 = $sattir['nameserv4'];
$esda_nameserv5 = $sattir['nameserv5'];
$esda_status1 = $sattir['status1'];
$esda_status2 = $sattir['status2'];
$esda_status3 = $sattir['status3'];
$esda_create_date = $sattir['create_date'];
$esda_update_date = $sattir['update_date'];
$esda_expirate_date = $sattir['expirate_date'];


$update_sorgu = "UPDATE `monitors` SET ";


/***************       register             ***********************/

if ($esda_register != $registrar) {

$update_sorgu .=" register  = '$registrar'  ";
$update_sorgu .=" ,
"
;

if ($mail_message == "") { $mail_message = "Change domain register    ".$esda_register." -->  ".$registrar."\n"; }
else if ($mail_message != "") { $mail_message .= "Change domain register    ".$esda_register." -->  ".$registrar."\n"; }
}

/***************       whois server             ***********************/

if ($esda_whois_serv != $whois_server) {

$update_sorgu .=" whois_serv = '$whois_server' ";
$update_sorgu .=" ,
"
;


if ($mail_message == "") { $mail_message = "Change whois server        ".$esda_whois_serv." -->  ".$whois_server."\n"; }
else if ($mail_message != "") { $mail_message .= "Change whois server        ".$esda_whois_serv." -->  ".$whois_server."\n"; }
}

/***************       referral url             ***********************/


if ($esda_ref_url != $referral_url) {
$update_sorgu .=" ref_url = '$referral_url' ";
$update_sorgu .=" ,
"
;


if ($mail_message == "") { $mail_message = "Change referral url        ".$esda_ref_url." -->  ".$referral_url."\n"; }
else if ($mail_message != "") { $mail_message .= "Change referral url        ".$esda_ref_url." -->  ".$referral_url."\n"; }
}


/***************       name server  1           ***********************/

if ($esda_nameserv1 != $name_server[1]) {
$update_sorgu .=" nameserv1 = '$name_server[1]' ";
$update_sorgu .=" ,
"
;


if ($mail_message == "") { $mail_message = "Change nameserver1        ".$esda_nameserv1." -->  ".$name_server[1]."\n"; }
else if ($mail_message != "") { $mail_message .= "Change nameserver1        ".$esda_nameserv1." -->  ".$name_server[1]."\n"; }
}

/***************       name server  2           ***********************/

if ($esda_nameserv2 != $name_server[2]) {
$update_sorgu .=" nameserv2 = '$name_server[2]' ";
$update_sorgu .=" ,
"
;


if ($mail_message == "") { $mail_message = "Change nameserver2        ".$esda_nameserv2." -->  ".$name_server[2]."\n"; }
else if ($mail_message != "") { $mail_message .= "Change nameserver2        ".$esda_nameserv2." -->  ".$name_server[2]."\n"; }
}

/***************       name server  3           ***********************/

if ($esda_nameserv3 != $name_server[3]) {
$update_sorgu .=" nameserv3 = '$name_server[3]' ";
$update_sorgu .=" ,
"
;


if ($mail_message == "") { $mail_message = "Change nameserver3        ".$esda_nameserv3." -->  ".$name_server[3]."\n"; }
else if ($mail_message != "") { $mail_message .= "Change nameserver3        ".$esda_nameserv3." -->  ".$name_server[3]."\n"; }
}

/***************       name server  4           ***********************/

if ($esda_nameserv4 != $name_server[4]) {
$update_sorgu .=" nameserv4 = '$name_server[4]' ";
$update_sorgu .=" ,
"
;


if ($mail_message == "") { $mail_message = "Change nameserver4        ".$esda_nameserv4." -->  ".$name_server[4]."\n"; }
else if ($mail_message != "") { $mail_message .= "Change nameserver4        ".$esda_nameserv4." -->  ".$name_server[4]."\n"; }
}

/***************       name server  5           ***********************/

if ($esda_nameserv5 != $name_server[5]) {
$update_sorgu .=" nameserv5 = '$name_server[5]' ";
$update_sorgu .=" ,
"
;


if ($mail_message == "") { $mail_message = "Change nameserver5        ".$esda_nameserv5." -->  ".$name_server[5]."\n"; }
else if ($mail_message != "") { $mail_message .= "Change nameserver5        ".$esda_nameserv5." -->  ".$name_server[5]."\n"; }
}

/***************       status 1         ***********************/

if ($esda_status1 != $status[1]) {

$update_sorgu .=" status1 = '$status[1]' ";
$update_sorgu .=" ,
"
;



if ($mail_message == "") { $mail_message = "Change status 1        ".$esda_status1." -->  ".$status[1]."\n"; }
else if ($mail_message != "") { $mail_message .= "Change status 1        ".$esda_status1." -->  ".$status[1]."\n"; }
}

/***************       status 2         ***********************/

if ($esda_status2 != $status[2]) {

$update_sorgu .=" status2 = '$status[2]'  ";
$update_sorgu .=" ,
"
;



if ($mail_message == "") { $mail_message = "Change status 2        ".$esda_status2." -->  ".$status[2]."\n"; }
else if ($mail_message != "") { $mail_message .= "Change status 2        ".$esda_status2." -->  ".$status[2]."\n"; }
}

/***************       status 3         ***********************/

if ($esda_status3 != $status[3]) {

$update_sorgu .=" status3 = '$status[3]' ";
$update_sorgu .=" ,
"
;



if ($mail_message == "") { $mail_message = "Change status 3        ".$esda_status3." -->  ".$status[3]."\n"; }
else if ($mail_message != "") { $mail_message .= "Change status 3        ".$esda_status3." -->  ".$status[3]."\n"; }
}

/***************       creation date         ***********************/

if ($esda_create_date != $creation_date) {

$update_sorgu .=" create_date = '$creation_date' ";
$update_sorgu .=" ,
"
;



if ($mail_message == "") { $mail_message = "Change creation date    ".$esda_create_date." -->  ".$creation_date."\n"; }
else if ($mail_message != "") { $mail_message .= "Change creation date        ".$esda_create_date." -->  ".$creation_date."\n"; }
}

/***************       updated date         ***********************/

if ($esda_update_date != $updated_date) {

$update_sorgu .=" update_date = '$updated_date' ";
$update_sorgu .=" ,
"
;



if ($mail_message == "") { $mail_message = "Change updated date        ".$esda_update_date." -->  ".$updated_date."\n"; }
else if ($mail_message != "") { $mail_message .= "Change updated date        ".$esda_update_date." -->  ".$updated_date."\n"; }
}

/***************       expiration date         ***********************/

if ($esda_expirate_date != $expiration_date) {

$update_sorgu .=" expirate_date = '$expiration_date' ";
 $update_sorgu .=" ,
"
;


if ($mail_message == "") { $mail_message = "Change expiration date        ".$esda_expirate_date." -->  ".$expiration_date."\n"; }
else if ($mail_message != "") { $mail_message .= "Change expiration date        ".$esda_expirate_date." -->  ".$expiration_date."\n"; }
}


$tarih = mktime (date ("H"), date ("i"), date ("s"), date("m"), date ("d"), date("Y"));
$hunter_update = date ("Y-m-d H:i:s", $tarih);


$update_sorgu .=" hunter_update = '$hunter_update' WHERE domain = '$target_domainss' ";

// echo $update_sorgu;


if ( ($bilgi_kontrol != 1) &amp;&amp; ($mail_message != "") ) {

$soru=mysql_query($update_sorgu) || die (mysql_error());



$send_message = "
Dear domain hunter user

Domain alert for $target_domainss

$mail_message

Thanks
Domain Hunter Control Systems
"
;



$subject = "Domain alert for $target_domainss"; //Subject of the e-mail

mail($hunter_email, $subject, $send_message, "From: Undisclosed-Recipient:;\nX-Mailer: PHP/" . phpversion());

}


} /// if end






} /// function end




?>


&amp;nbsp;