Category Archives: Mod-rewrite

Websites using Multilanguage system Mod_rewrite

JobFlexer is a software platform which very easy in use. This platform gave you opportunity to create website in few simple steps. Create your own websites using Multilanguage system in JobFlexer software platform.
Using a flexible system of working with the forms you will not be difficult to adjust itself to filling in the fields of registration forms or forms for posting resumes and jobs.

 

 

<?php

class Mpermissions extends Model {

 /**================================================================================================================
 *    PERMISSIONS START
 *=================================================================================================================*/


 /**
 * Deletes a permission
 *
 * @param int $ID
 * @return bol
 */


 function delete_permission ( $ID )
 {
 $query = $this->db->query
 (
 'SELECT
 *
 FROM
 '
. DBPREFIX . 'permissions
 WHERE
 parent_id = '
. qstr ( $ID )
 );

 if ( $query->num_rows () > 0 ) {
 foreach ( $query->result () as $row ) {
 $this->delete_permission ( $row->ID );
 }
 }

 return ( $this->db->query
 (
 "DELETE FROM
 "
. DBPREFIX . "permissions
 WHERE
 `ID` = "
. qstr ( $ID )
 ) ) ? TRUE : FALSE;
 }

 /**
 * get_child_permissions_array
 *
 * Used to compare what the admin submits for a group
 * or user. If he selected all the labels there's no need
 * to create an entry for each and every one of them but
 * instead, we enter the parrent. To determine that, we will
 * compared the _POST array with what's in the permissions's
 * table.
 *
 * @param int $parent - the parent id
 * @return array
 */


 function get_child_permissions_array ( $parent )
 {
 $query = $this->db->query
 (
 'SELECT
 *
 FROM
 '
. DBPREFIX . 'permissions
 WHERE parent_id = '
. qstr ( $parent )
 );

 $array = array ();

 if ( $query->num_rows () > 0 )
 {
 foreach ( $query->result () as $row )
 {
 $array [] = $row->ID;
 }
 }

 return ( count ( $array ) > 0 ) ? $array : FALSE;
 }

 function _get_child_permissions_array ( $parent )
 {
 $query = $this->db->query
 (
 'SELECT
 *
 FROM
 '
. DBPREFIX . 'permissions
 WHERE parent_id = '
. qstr ( $parent )
 );

 $array = array ();

 if ( $query->num_rows () > 0 )
 {
 foreach (  $query->result () as $row  )
 {
 $array [] = $row;
 }
 }

 return ( count ( $array ) > 0 ) ? $array : FALSE;
 }

 /**
 * Returns the permission details
 *
 * @param int $id
 * @return obj
 */


 function get_permission ( $id )
 {
 $query = $this->db->query
 (
 'SELECT
 *
 FROM
 '
. DBPREFIX . 'permissions
 WHERE
 ID = '
. qstr ( $id )
 );
 return ( $query->num_rows () == 1 ) ? $query->row () : FALSE;
 }

 /**
 * Deletes all permissions assigned to a specific group
 * or use
 *
 * @param int $id - group id
 * @return bol
 */


 function delete_all_permissions ( $id, $type )
 {
 return (  $this->db->query
 (
 'DELETE
 FROM
 '
. DBPREFIX . 'added_permissions
 WHERE
 item_id = '
. qstr ( $id ) . '
 AND item_type = '
. qstr ( $type )
 )
 ) ? TRUE : FALSE;
 }

 /**
 * Inserts a permission
 *
 * @param int $group - user id
 * @param int $area - the area
 * @param int $item_type - group or user
 * @return bol
 */


 function add_permission ( $item_id, $area, $item_type )
 {
 $data = array
 (
 'item_id'    =>    $item_id,
 'item_type'    =>    $item_type,
 'area'        =>    $area
 );

 return ( $this->db->insert ( DBPREFIX . 'added_permissions', escape_arr ( $data ) ) ) ? TRUE : FALSE;
 }

 // ------------------------------------------------------------------------

 /**
 * get_permission_parent_id
 *
 * Returns the parent id of a given permission
 *
 * @param    perm id
 * @access    private
 * @return     int
 */


 function get_permission_parent_id ( $id )
 {
 $query = $this->db->query ( 'SELECT parent_id from ' . DBPREFIX . 'permissions WHERE ID = ' . qstr ( $id ) );
 if ( $query->num_rows () == 1 ) {
 $row = $query->row ();
 return $row->parent_id;
 }
 return FALSE;
 }

 // ------------------------------------------------------------------------

 /**
 * check_permission_record
 *
 * Returns true or false if a permission was set for the
 * following group or user
 *
 * @param    $area - area id
 * @param    $type - group/user
 * @param    $id - id of the user or group
 * @access    private
 * @return     bol
 */


 function check_permission_record ( $area, $type, $id )
 {
 switch ( $type )
 {
 case 'user':
 $query = $this->db->query ( 'SELECT ID FROM ' . DBPREFIX . 'added_permissions WHERE item_id = ' . qstr ( $id ) . ' AND area = ' . qstr ( $area ) . ' AND item_type = ' . qstr ( $type ) );

 return ( $query->num_rows () == 1 ) ? TRUE : FALSE;
 break;

 case 'group':
 $query = $this->db->query ( 'SELECT ID FROM ' . DBPREFIX . 'added_permissions WHERE item_id = ' . qstr ( $id ) . ' AND area = ' . qstr ( $area ) . ' AND item_type = ' . qstr ( $type ) );

 return ( $query->num_rows () == 1  ) ? TRUE : FALSE;
 break;
 }
 }

 // ------------------------------------------------------------------------

 /**
 * check_parent_permission_record
 *
 * Returns true or false if a parent permission was set for the
 * following group or user
 *
 * @param    $area - area id
 * @param    $type - group/user
 * @param    $id - id of the user or group
 * @access    private
 * @return     bol
 */


 function check_parent_permission_record ( $area, $type, $id )
 {
 switch ( $type )
 {
 case 'user':
 $query = $this->db->query ( 'SELECT ID FROM ' . DBPREFIX . 'added_permissions WHERE item_id = ' . qstr ( $id ) . ' AND area = ' . qstr ( $this->get_permission_parent_id ( $area ) ) . ' AND item_type = ' . qstr ( $type ) );

 return ( $query->num_rows () == 1 ) ? TRUE : FALSE;
 break;

 case 'group':
 $query = $this->db->query ( 'SELECT ID FROM ' . DBPREFIX . 'added_permissions WHERE item_id = ' . qstr ( $id ) . ' AND area = ' . qstr ( $this->get_permission_parent_id ( $area ) ) . ' AND item_type = ' . qstr ( $type ) );

 return ( $query->num_rows () == 1  ) ? TRUE : FALSE;
 break;
 }
 }

 /**
 * Tryes to determine if a given permission is parent or not
 *
 * @param int $id
 * @return bol
 */


 function is_parent_permission ( $id )
 {
 $query = $this->db->query
 (
 'SELECT
 *
 FROM
 '
. DBPREFIX . 'permissions
 WHERE
 ID = '
. qstr ( $id )
 );
 if ( $query->num_rows () == 1 ) {
 $row = $query->row ();
 if ( $row->parent_id == 0 ) {
 return TRUE;
 }
 return FALSE;
 }
 return FALSE;
 }

 // ------------------------------------------------------------------------

 /**
 * get_parent_permissions
 *
 * Returns the current parent permissions
 *
 * @param    none
 * @access    private
 * @return     obj
 */


 function get_parent_permissions ( $cache = TRUE )
 {
 return $this->db->query
 (     'SELECT
 *
 FROM
 '
. DBPREFIX . 'permissions
 WHERE
 parent_id = 0
 ORDER BY
 ID DESC'

 );
 }

 // ------------------------------------------------------------------------

 /**
 * get_childs_permissions
 *
 * Returns the current permissions
 *
 * @param    $parent_id - the parent ID
 * @access    private
 * @return     obj
 */


 function get_childs_permissions ( $parent_id )
 {
 return $this->db->query
 (     'SELECT
 *
 FROM
 '
. DBPREFIX . 'permissions
 WHERE
 parent_id = '
. qstr ( $parent_id ) . '
 ORDER BY
 ID ASC'

 );
 }

 /**
 * Adds new permissions or permission rules to the database
 *
 * @param $parent -     if the parent is 0 we have a new permission
 *             otherwise add a child to an existing permission
 * @return int/bol
 */


 function add_new_permission ( $label, $parent = 0 )
 {
 $data = array
 (
 'label'        =>    $label,
 'parent_id'    =>    $parent,
 'editable'    =>    1
 );
 return ( $this->db->insert ( DBPREFIX . 'permissions', escape_arr ( $data ) ) ) ? $this->db->call_function ( 'insert_id' ) : FALSE;
 }

 /**
 * Updates a permission
 *
 * @param $label - permission label
 * @param $parent -     if the parent is 0 we have a new permission
 *             otherwise add a child to an existing permission
 * @return int/bol
 */


 function update_permission ( $id, $label )
 {
 $data = array
 (
 'label'        =>    $label
 );
 $this->db->where ( 'ID', $id );
 return ( $this->db->update ( DBPREFIX . 'permissions', escape_arr ( $data ) ) ) ? TRUE : FALSE;
 }

 function get_all_permissions ()
 {
 $query = $this->db->query
 (
 'SELECT
 ID, parent_id
 FROM
 '
. DBPREFIX . 'permissions'
 );
 return ( $query->num_rows () > 0 ) ? $query->result () : FALSE;
 }

 /**================================================================================================================
 *    PERMISSIONS END
 *=================================================================================================================*/


}
//END

&amp;nbsp;

PHP scripts for maintaining PAD enabled sites

‘PAD Site Scripts’ is a commercial set of PHP scripts for maintaining PAD enabled sites for Windows™ software downloads. It was initially based on PADKit (currently suspended), a free PAD enabled PHP/MySQL shareware download site kit, developed and supported by ASP (Association of Software Professionals). Hovewer, all the existing scripts have been completely rewritten and new scripts/modules added to implement several important features missing in the original source.

 

 

<?php

class Mcolors extends Model {

 function add ( $color, $occurences = 1 )
 {
 $this->db->query ( 'INSERT INTO ' . DBPREFIX . 'colors (`color`,`occurences`) VALUES (' . qstr ( $color ) . ',' . qstr ( ( int ) $occurences ) . ') ON DUPLICATE KEY UPDATE ID=LAST_INSERT_ID(ID), occurences=occurences+1' );
 return $this->db->call_function ( 'insert_id' );
 }

 function add_rel ( $color_id, $wall_id )
 {
 $this->db->query ( 'INSERT IGNORE INTO ' . DBPREFIX . 'colors_rel (`color_id`,`item_id`) VALUES (' . qstr ( ( int ) $color_id ) . ',' . qstr ( ( int ) $wall_id ) . ')' );
 return $this->db->call_function ( 'insert_id' );
 }

 function get_color_data ()
 {
 $query = $this->db->query
 (
 'SELECT
 DISTINCT color
 FROM
 '
. DBPREFIX . 'colors
 ORDER BY
 RAND()
 LIMIT 0, '
. MAX_COLORS
 );

 return ( $query->num_rows () ) ? $query->result () : FALSE;
 }

 function delete_by_wallpaper ( $wallpaper_id )
 {
 return ( $this->db->query ( 'DELETE FROM ' . DBPREFIX . 'colors_rel WHERE item_id = ' . qstr ( $wallpaper_id ) ) ) ? TRUE : FALSE;
 }

 function get_wallpapers_by_color ( $color )
 {
 $query = $this->db->query
 (
 'SELECT
 w.*
 FROM
 '
. DBPREFIX . 'colors_rel r
 INNER JOIN
 '
. DBPREFIX . 'wallpapers w
 ON
 (
 r.item_id = w.ID
 )
 INNER JOIN
 '
. DBPREFIX . 'colors c
 ON
 (
 r.color_id = c.ID
 )
 WHERE r.item_id = '
. qstr ( ( int ) $color )
 );

 return ( $query->num_rows () ) ? $query->result () : FALSE;
 }

 function get_wallpaper_colors ( $wall_id )
 {
 $query = $this->db->query
 (
 'SELECT
 c.color,
 c.ID
 FROM
 '
. DBPREFIX . 'colors_rel r
 INNER JOIN
 '
. DBPREFIX . 'colors c
 ON
 (
 c.ID = r.color_id
 )
 WHERE r.item_id = '
. qstr ( ( int ) $wall_id ) . ' LIMIT 0, 18'
 );

 return ( $query->num_rows () ) ? $query->result () : FALSE;
 }

 function update_colors ()
 {
 $query = $this->db->query
 (
 'SELECT
 c.ID,
 c.occurences,
 COUNT(r.color_id) AS r_occurences,
 r.item_id as item_id,
 w.ID as wall_id
 FROM
 '
. DBPREFIX . 'colors c
 LEFT JOIN
 '
. DBPREFIX . 'colors_rel r
 ON
 (
 r.color_id = c.ID
 )
 LEFT JOIN
 '
. DBPREFIX . 'wallpapers w
 ON
 (
 w.id = r.item_id
 )
 GROUP BY
 c.ID
 HAVING
 r_occurences <> occurences OR wall_id IS NULL LIMIT 0, 200'

 );

 if ( $query->num_rows () ) {
 foreach ( $query->result () AS $row ) {
 if ( $row->wall_id == NULL ) {
 $this->db->query ( 'DELETE FROM ' . DBPREFIX . 'colors_rel WHERE item_id = ' . qstr ( ( int ) $row->item_id ) );
 if ( $row->r_occurences ) {
 $row->r_occurences -= 1;
 }
 }

 if ( ! ( bool ) $row->r_occurences ) {
 $this->db->query ( 'DELETE FROM ' . DBPREFIX . 'colors WHERE ID = ' . qstr ( ( int ) $row->ID ) );
 }
 else {
 $this->db->query ( 'UPDATE ' . DBPREFIX . 'colors SET occurences = ' . qstr ( ( int ) $row->r_occurences ) . ' WHERE ID = ' . qstr ( ( int ) $row->ID ) );
 }
 }
 }

 return $query->num_rows ();
 }
}

//END

&amp;nbsp;

SEO PHP Reciprocal Script for Mod_rewrite

Automatic Link Exchange Script Enhances your search engine standing. Increasing link popularity. 100% automatic link checker makes this script very special. Automatically keeps checking for link backs and notifies you when your link is removed by any link partner.

 

 

<?php
@session_start ();

/*
|---------------------------------------------------------------
| FIRST CHECK
|---------------------------------------------------------------
|
| Try to determine if we need an install otherwise continue
|
*/

 if ( file_exists ( 'settings.php' ) &amp;&amp; filesize ( 'settings.php' ) > 100 )
 {
 if ( is_dir ( 'install' ) )
 {
 die ( "Please delete the folder \"install\" from your server before continuing!" );
 }

 require_once ( 'settings.php' );
 require_once ( 'watermark.php' );
 }
 else {
 header ( "Location: install/install.php" );
 die ();//prevent anything else
 }

/*
|---------------------------------------------------------------
| PHP ERROR REPORTING LEVEL
|---------------------------------------------------------------
|
| By default CI runs with error reporting set to ALL.  For security
| reasons you are encouraged to change this when your site goes live.
| For more info visit:  http://www.php.net/error_reporting
|
*/

 error_reporting ( ( RUN_ON_DEVELOPMENT ) ? E_ALL : E_WARNING );
 @ini_set ( "display_errors",RUN_ON_DEVELOPMENT );

/*
|---------------------------------------------------------------
| SYSTEM FOLDER NAME
|---------------------------------------------------------------
|
| This variable must contain the name of your "system" folder.
| Include the path if the folder is not in the same  directory
| as this file.
|
| NO TRAILING SLASH!
|
*/

 $system_folder = "system";

/*
|---------------------------------------------------------------
| APPLICATION FOLDER NAME
|---------------------------------------------------------------
|
| If you want this front controller to use a different "application"
| folder then the default one you can set its name here. The folder
| can also be renamed or relocated anywhere on your server.
| For more info please see the user guide:
| http://www.codeigniter.com/user_guide/general/managing_apps.html
|
|
| NO TRAILING SLASH!
|
*/

 $application_folder = "application";


/*
|===============================================================
| END OF USER CONFIGURABLE SETTINGS
|===============================================================
*/



/*
|---------------------------------------------------------------
| SET THE SERVER PATH
|---------------------------------------------------------------
|
| Let's attempt to determine the full-server path to the "system"
| folder in order to reduce the possibility of path problems.
| Note: We only attempt this if the user hasn't specified a
| full server path.
|
*/

 if (strpos($system_folder, '/') === FALSE)
 {
 if (function_exists('realpath') AND @realpath(dirname(__FILE__)) !== FALSE)
 {
 $system_folder = realpath(dirname(__FILE__)).'/'.$system_folder;
 }
 }
 else
 {
 // Swap directory separators to Unix style for consistency
 $system_folder = str_replace("\\", "/", $system_folder);
 }

/*
|---------------------------------------------------------------
| DEFINE APPLICATION CONSTANTS
|---------------------------------------------------------------
|
| EXT        - The file extension.  Typically ".php"
| FCPATH    - The full server path to THIS file
| SELF        - The name of THIS file (typically "index.php)
| BASEPATH    - The full server path to the "system" folder
| APPPATH    - The full server path to the "application" folder
|
*/

 define ( 'EXT', '.'.pathinfo ( __FILE__, PATHINFO_EXTENSION ) );
 define ( 'FCPATH', __FILE__ );
 define ( 'SELF', pathinfo( __FILE__, PATHINFO_BASENAME ) );
 define ( 'BASEPATH', $system_folder.'/');
 define ( 'ROOTPATH', realpath ( dirname ( BASEPATH ) ) );

 $phpver = (float) PHP_VERSION;
 if ( $phpver >= 5.0 ) {
 define( 'PHPVER',0x5000);
 }
 elseif ( $phpver > 4.299999 ) { # 4.3
define( 'PHPVER',0x4300);
 }
 elseif ( $phpver > 4.199999 ) { # 4.2
define( 'PHPVER',0x4200);
 }
 elseif ( strnatcmp ( PHP_VERSION,'4.0.5' ) >=0 ) {
 define( 'PHPVER',0x4050);
 }
 else {
 define( 'PHPVER',0x4000);
 }

 if (is_dir($application_folder))
 {
 define('APPPATH', $application_folder.'/');
 }
 else
 {
 if ($application_folder == '')
 {
 $application_folder = 'application';
 }

 define('APPPATH', BASEPATH.$application_folder.'/');
 }

/*
|---------------------------------------------------------------
| DEFINE E_STRICT
|---------------------------------------------------------------
|
| Some older versions of PHP don't support the E_STRICT constant
| so we need to explicitly define it otherwise the Exception class
| will generate errors.
|
*/

 if ( ! defined('E_STRICT'))
 {
 define('E_STRICT', 2048);
 }

 define ( 'SMARTY_TEMPLATE_DIR', ROOTPATH . '/templates/' );
 //    when you chnage this remember to also change in scripts/combine.php
 define ( 'TEMP_DIR', ROOTPATH . '/various/cache/' );
 define ( 'LOGS_DIR', ROOTPATH . '/various/logs/' );
 define ( 'MODULES_DIR', APPPATH . 'modules/' );
 define ( 'SMARTY_COMPILE_DIR', TEMP_DIR );
 define ( 'SMARTY_CACHE_DIR', TEMP_DIR );
 define ( 'DB_CACHE_DIR', TEMP_DIR );
 define ( 'WS_ENCODING', 'UTF-8' );

 if ( extension_loaded ( 'mbstring' ) ) {
 define ( 'MB_LOADED', TRUE );
 @mb_regex_set_options ( 'pz' );
 @mb_internal_encoding ( WS_ENCODING );
 @mb_regex_encoding ( WS_ENCODING );
 }
 else {
 define ( 'MB_LOADED', FALSE );
 }

/*
|---------------------------------------------------------------
| INI COMMANDS
|---------------------------------------------------------------
|
| The script requires a little more memory to run without
| errors so we'll try to make sure we're not running out
| of it.
|
*/


 define ( 'SAFE_MODE', ( ( bool ) @ini_get ( "safe_mode" ) === FALSE ) ? FALSE : TRUE );
 define ( 'MEMORY_LIMIT', '128M' );

 if ( ! SAFE_MODE ) {
 @ini_set ( 'memory_limit', MEMORY_LIMIT );
 }

 define ( "GLOBAL_PREFIX", "WS_" );
 define ( "AUTH_COOKIE", GLOBAL_PREFIX . "authenticate" );
 define ( "AUTH_COOKIE_ID", GLOBAL_PREFIX . "cookie_id" );
 define ( "AUTH_SESSION_ID", GLOBAL_PREFIX . "user_id" );
 define ( "LOGGEDIN", GLOBAL_PREFIX . "logged_in" );
 define ( "BASE_PATH", "" );
 define ( "COOKIE_PATH", "/" );
 define ( "ATEMPT", GLOBAL_PREFIX . "attempt" );

/*
|---------------------------------------------------------------
| LOAD THE FRONT CONTROLLER
|---------------------------------------------------------------
|
| And away we go...
|
*/

 require_once BASEPATH . 'codeigniter/CodeIgniter'.EXT;
//END

&amp;nbsp;

PHP URL Rewriting Without Apache and mod_rewrite

At that point I started being concerned about the deadline especially after the amount of time and effort put into developing the site. I took a 10 minute break and tried thinking of a solution.I don’t recommend using the approach I’m about to explain unless it’s necessary and you’re in a situation like I was with no alternative.Through H-Sphere I was able to set up a custom error page. I decided to create a PHP script as the error page and used that as my “rewrite” method (it’s technically not rewriting but still). I didn’t want the script to re-direct the user, that would defeat the point of doing this, and after checking the server wasn’t sending a 404 header and decided to do it.

 

 

<?php

/* Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ )
 Manual: http://scripts.incutio.com/httpclient/
*/


class HttpClient {
 // Request vars
 var $host;
 var $port;
 var $path;
 var $method;
 var $postdata = '';
 var $cookies = array();
 var $referer;
 var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
 var $accept_encoding = 'gzip';
 var $accept_language = 'en-us';
 var $user_agent = 'Incutio HttpClient v0.9';
 // Options
 var $timeout = 20;
 var $use_gzip = true;
 var $persist_cookies = true;  // If true, received cookies are placed in the $this->cookies array ready for the next request
 // Note: This currently ignores the cookie path (and time) completely. Time is not important,
 //       but path could possibly lead to security problems.
 var $persist_referers = true; // For each request, sends path of last request as referer
 var $debug = false;
 var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found
 var $max_redirects = 5;
 var $headers_only = false;    // If true, stops receiving once headers have been read.
 // Basic authorization variables
 var $username;
 var $password;
 // Response vars
 var $status;
 var $headers = array();
 var $content = '';
 var $errormsg;
 // Tracker variables
 var $redirect_count = 0;
 var $cookie_host = '';
 function HttpClient($host, $port=80) {
 $this->host = $host;
 $this->port = $port;
 }
 function get($path, $data = false) {
 $this->path = $path;
 $this->method = 'GET';
 if ($data) {
 $this->path .= '?'.$this->buildQueryString($data);
 }
 return $this->doRequest();
 }
 function post($path, $data) {
 $this->path = $path;
 $this->method = 'POST';
 $this->postdata = $this->buildQueryString($data);
 return $this->doRequest();
 }
 function buildQueryString($data) {
 $querystring = '';
 if (is_array($data)) {
 // Change data in to postable data
 foreach ($data as $key => $val) {
 if (is_array($val)) {
 foreach ($val as $val2) {
 $querystring .= urlencode($key).'='.urlencode($val2).'&amp;';
 }
 } else {
 $querystring .= urlencode($key).'='.urlencode($val).'&amp;';
 }
 }
 $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &amp;
 } else {
 $querystring = $data;
 }
 return $querystring;
 }
 function doRequest() {
 // Performs the actual HTTP request, returning true or false depending on outcome
 if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
 // Set error message
 switch($errno) {
 case -3:
 $this->errormsg = 'Socket creation failed (-3)';
 case -4:
 $this->errormsg = 'DNS lookup failure (-4)';
 case -5:
 $this->errormsg = 'Connection refused or timed out (-5)';
 default:
 $this->errormsg = 'Connection failed ('.$errno.')';
 $this->errormsg .= ' '.$errstr;
 $this->debug($this->errormsg);
 }
 return false;
 }
 socket_set_timeout($fp, $this->timeout);
 $request = $this->buildRequest();
 $this->debug('Request', $request);
 fwrite($fp, $request);
 // Reset all the variables that should not persist between requests
 $this->headers = array();
 $this->content = '';
 $this->errormsg = '';
 // Set a couple of flags
 $inHeaders = true;
 $atStart = true;
 // Now start reading back the response
 while (!feof($fp)) {
 $line = fgets($fp, 4096);
 if ($atStart) {
 // Deal with first line of returned data
 $atStart = false;
 if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
 $this->errormsg = "Status code line invalid: ".htmlentities($line);
 $this->debug($this->errormsg);
 return false;
 }
 $http_version = $m[1]; // not used
 $this->status = $m[2];
 $status_string = $m[3]; // not used
 $this->debug(trim($line));
 continue;
 }
 if ($inHeaders) {
 if (trim($line) == '') {
 $inHeaders = false;
 $this->debug('Received Headers', $this->headers);
 if ($this->headers_only) {
 break; // Skip the rest of the input
 }
 continue;
 }
 if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
 // Skip to the next header
 continue;
 }
 $key = strtolower(trim($m[1]));
 $val = trim($m[2]);
 // Deal with the possibility of multiple headers of same name
 if (isset($this->headers[$key])) {
 if (is_array($this->headers[$key])) {
 $this->headers[$key][] = $val;
 } else {
 $this->headers[$key] = array($this->headers[$key], $val);
 }
 } else {
 $this->headers[$key] = $val;
 }
 continue;
 }
 // We're not in the headers, so append the line to the contents
 $this->content .= $line;
 }
 fclose($fp);
 // If data is compressed, uncompress it
 if (isset($this->headers['content-encoding']) &amp;&amp; $this->headers['content-encoding'] == 'gzip') {
 $this->debug('Content is gzip encoded, unzipping it');
 $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php
 $this->content = gzinflate($this->content);
 }
 // If $persist_cookies, deal with any cookies
 if ($this->persist_cookies &amp;&amp; isset($this->headers['set-cookie']) &amp;&amp; $this->host == $this->cookie_host) {
 $cookies = $this->headers['set-cookie'];
 if (!is_array($cookies)) {
 $cookies = array($cookies);
 }
 foreach ($cookies as $cookie) {
 if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
 $this->cookies[$m[1]] = $m[2];
 }
 }
 // Record domain of cookies for security reasons
 $this->cookie_host = $this->host;
 }
 // If $persist_referers, set the referer ready for the next request
 if ($this->persist_referers) {
 $this->debug('Persisting referer: '.$this->getRequestURL());
 $this->referer = $this->getRequestURL();
 }
 // Finally, if handle_redirects and a redirect is sent, do that
 if ($this->handle_redirects) {
 if (++$this->redirect_count >= $this->max_redirects) {
 $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')';
 $this->debug($this->errormsg);
 $this->redirect_count = 0;
 return false;
 }
 $location = isset($this->headers['location']) ? $this->headers['location'] : '';
 $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
 if ($location || $uri) {
 $url = parse_url($location.$uri);
 // This will FAIL if redirect is to a different site
 return $this->get($url['path']);
 }
 }
 return true;
 }
 function buildRequest() {
 $headers = array();
 $headers[] = "{$this->method} {$this->path} HTTP/1.0"; // Using 1.1 leads to all manner of problems, such as "chunked" encoding
 $headers[] = "Host: {$this->host}";
 $headers[] = "User-Agent: {$this->user_agent}";
 $headers[] = "Accept: {$this->accept}";
 if ($this->use_gzip) {
 $headers[] = "Accept-encoding: {$this->accept_encoding}";
 }
 $headers[] = "Accept-language: {$this->accept_language}";
 if ($this->referer) {
 $headers[] = "Referer: {$this->referer}";
 }
 // Cookies
 if ($this->cookies) {
 $cookie = 'Cookie: ';
 foreach ($this->cookies as $key => $value) {
 $cookie .= "$key=$value; ";
 }
 $headers[] = $cookie;
 }
 // Basic authentication
 if ($this->username &amp;&amp; $this->password) {
 $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
 }
 // If this is a POST, set the content type and length
 if ($this->postdata) {
 $headers[] = 'Content-Type: application/x-www-form-urlencoded';
 $headers[] = 'Content-Length: '.strlen($this->postdata);
 }
 $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
 return $request;
 }
 function getStatus() {
 return $this->status;
 }
 function getContent() {
 return $this->content;
 }
 function getHeaders() {
 return $this->headers;
 }
 function getHeader($header) {
 $header = strtolower($header);
 if (isset($this->headers[$header])) {
 return $this->headers[$header];
 } else {
 return false;
 }
 }
 function getError() {
 return $this->errormsg;
 }
 function getCookies() {
 return $this->cookies;
 }
 function getRequestURL() {
 $url = 'http://'.$this->host;
 if ($this->port != 80) {
 $url .= ':'.$this->port;
 }
 $url .= $this->path;
 return $url;
 }
 // Setter methods
 function setUserAgent($string) {
 $this->user_agent = $string;
 }
 function setAuthorization($username, $password) {
 $this->username = $username;
 $this->password = $password;
 }
 function setCookies($array) {
 $this->cookies = $array;
 }
 // Option setting methods
 function useGzip($boolean) {
 $this->use_gzip = $boolean;
 }
 function setPersistCookies($boolean) {
 $this->persist_cookies = $boolean;
 }
 function setPersistReferers($boolean) {
 $this->persist_referers = $boolean;
 }
 function setHandleRedirects($boolean) {
 $this->handle_redirects = $boolean;
 }
 function setMaxRedirects($num) {
 $this->max_redirects = $num;
 }
 function setHeadersOnly($boolean) {
 $this->headers_only = $boolean;
 }
 function setDebug($boolean) {
 $this->debug = $boolean;
 }
 // "Quick" static methods
 function quickGet($url) {
 $bits = parse_url($url);
 $host = $bits['host'];
 $port = isset($bits['port']) ? $bits['port'] : 80;
 $path = isset($bits['path']) ? $bits['path'] : '/';
 if (isset($bits['query'])) {
 $path .= '?'.$bits['query'];
 }
 $client = new HttpClient($host, $port);
 if (!$client->get($path)) {
 return false;
 } else {
 return $client->getContent();
 }
 }
 function quickPost($url, $data) {
 $bits = parse_url($url);
 $host = $bits['host'];
 $port = isset($bits['port']) ? $bits['port'] : 80;
 $path = isset($bits['path']) ? $bits['path'] : '/';
 $client = new HttpClient($host, $port);
 if (!$client->post($path, $data)) {
 return false;
 } else {
 return $client->getContent();
 }
 }
 function debug($msg, $object = false) {
 if ($this->debug) {
 print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg;
 if ($object) {
 ob_start();
 print_r($object);
 $content = htmlentities(ob_get_contents());
 ob_end_clean();
 print '<pre>'.$content.'</pre>';
 }
 print '</div>';
 }
 }
}

?>

&amp;nbsp;

PHP mod_rewrite Content Management System

If you got a CMS site or blog site that has dynamic URLs and want a free mod_rewrite version of the scripts, post a link to the site distributing the CMS/blog and I’ll see about making it SEO friendly, and give you access to future upgrades if you want them. The only requirement is that the script is under the General Public License (GPL) or another similar License.

 

 

<?php
$phpver = ( float ) PHP_VERSION;
if ( $phpver >= 5.0 ) {
 define ( 'PHPVER', 0x5000 );
}
elseif ( $phpver > 4.299999 ) { # 4.3
define ( 'PHPVER', 0x4300 );
}
elseif ( $phpver > 4.199999 ) { # 4.2
define ( 'PHPVER', 0x4200 );
}
elseif ( strnatcmp ( PHP_VERSION, '4.0.5' ) >= 0 ) {
 define ( 'PHPVER', 0x4050 );
}
else {
 define ( 'PHPVER', 0x4000 );
}

function site_url () {
}

function qstr ( $str, $magic_quotes = false ) {
 switch ( gettype ( $str ) ) {
 case 'string' :
 $replaceQuote = "\'"; /// string to use to replace quotes
 if ( ! $magic_quotes ) {

 if ( $replaceQuote [ 0 ] == '\' ) {
 // only since php 4.0.5
 $str = _str_replace ( array (
 '
\', "&#092;&#048;"
 ), array (
 '
\\\', "\\&#092;&#048;"
 ), $str );
 //$s = str_replace("&#092;&#048;","\\&#092;&#048;", str_replace('
\','\\\',$s));
 }
 return "'
" . str_replace ( "'", $replaceQuote, $str ) . "'";
 }

 // undo magic quotes for "

 $str = str_replace ( '\\"', '"', $str );

 if ( $replaceQuote == "\'" ) { // ' already quoted, no need to change anything
 return "'$str'";
 }
 else { // change \' to '' for sybase/mssql
 $str = str_replace ( '\\\', '\', $str );
 return "'
" . str_replace ( "\'", $treplaceQuote, $str ) . "'";
 }
 break;
 case 'boolean' :
 $str = ( $str === FALSE ) ? 0 : 1;
 return $str;
 break;
 case 'integer' :
 $str = ( $str === NULL ) ? 'NULL' : $str;
 return $str;
 break;
 default :
 $str = ( $str === NULL ) ? 'NULL' : $str;
 return $str;
 break;
 }
}

function escape_arr ( $array ) {
 if ( is_array ( $array ) ) {
 foreach ( $array as $key => $value ) {
 $new_arr [ $key ] = addslashes ( $value );
 }
 return $new_arr;
 }
}

function _str_replace ( $src, $dest, $data ) {
 if ( PHPVER >= 0x4050 )
 return str_replace ( $src, $dest, $data );

 $s = reset ( $src );
 $d = reset ( $dest );
 while ( $s !== false ) {
 $data = str_replace ( $s, $d, $data );
 $s = next ( $src );
 $d = next ( $dest );
 }
 return $data;
}

function prepare_constant ( $input, $bolean = FALSE ) {
 return ( $bolean ) ? ( ( $input == 1 ) ? 'TRUE' : 'FALSE' ) : "
'" . addslashes ( $input ) . "'";
}

function add_ending_slash ( $string ) {
 return ( preg_match ( '/\/$/', $string ) ) ? $string : $string . '/';
}

function Lang ( $key ) {
 $lang = LoadLanguage ( 'en' );
 if ( isset ( $lang [ $key ] ) ) {
 return $lang [ $key ];
 }
 else {
 return "
Language string failed to load: " . $key;
 }
}

function LoadLanguage ( $lang_type ) {
 include ( "
../language/english.php" );
 return $lang;
}

function load_permission_files () {
 include ( '../system/application/config/file_permissions.php' );
 return $permArray;
}

function Verify_files_before_install () {
 $permError = '';
 $serverError = '';
 $isOK = true;
 $permArray = load_permission_files ();

 $linux_message = 'Please CHMOD it to 777.';
 $windows_message = 'Please set anonymous write permissions in IIS. If you don\'t have access to do this, you will need to contact your hosting provider.';

 $error_message = $linux_message;
 if ( strtolower ( substr ( PHP_OS, 0, 3 ) ) == 'win' ) {
 $error_message = $windows_message;
 }

 foreach ( $permArray as $a ) {
 if ( ! _is_really_writable ( '../' . $a ) ) {
 $permError .= sprintf ( "
<div class=\"error_messages\"><p>The file or folder <b>%s</b> isn't writable. " . $error_message . "</p></div>", $a );
 $isOK = false;
 }
 }

 if ( ! $isOK ) {
 return $permError;
 }
 return TRUE;
}

function add_start_end_slashes ( $input ) {
 if ( $input != '' ) {
 if ( substr ( $input, - 1 ) != '/' ) {
 $input = $input . '/';
 }

 if ( substr ( $input, 0, 1 ) != '/' ) {
 $input = '/' . $input;
 }
 return $input;
 }
}

function print_unique_id () {
 $prefix = 'W';
 $my_random_id = $prefix;
 $my_random_id .= chr ( rand ( 65, 90 ) );
 $my_random_id .= time ();
 $my_random_id .= uniqid ( $prefix );
 return $my_random_id;
}

function get_domain_of_url ( $url ) {
 $parse = @parse_url ( $url );
 return $parse [ 'host' ];
}

function _is_really_writable ( $file ) {
 if ( is_dir ( $file ) ) {
 $file = rtrim ( $file, '/' ) . '/' . md5 ( rand ( 1, 100 ) );

 if ( ( $fp = @fopen ( $file, 'ab' ) ) === FALSE ) {
 return FALSE;
 }

 fclose ( $fp );
 @chmod ( $file, 0777 );
 @unlink ( $file );
 return TRUE;
 }
 elseif ( ( $fp = @fopen ( $file, 'ab' ) ) === FALSE ) {
 return FALSE;
 }

 fclose ( $fp );
 return TRUE;
}

function application_url ( $path = null ) {
 $s = empty ( $_SERVER [ 'HTTPS' ] ) ? '' : ( $_SERVER [ 'HTTPS' ] == 'on' ) ? 's' : '';
 $protocol = application_url_strleft ( strtolower ( $_SERVER [ 'SERVER_PROTOCOL' ] ), '/' ) . $s;
 $port = ( $_SERVER [ 'SERVER_PORT' ] == '80' ) ? '' : ( ':' . $_SERVER [ 'SERVER_PORT' ] );
 return $protocol . '://' . $_SERVER [ 'SERVER_NAME' ] . $port . dirname ( $_SERVER [ 'SCRIPT_NAME' ] ) . '/' . $path;
}

function application_url_strleft ( $s1, $s2 ) {
 return substr ( $s1, 0, strpos ( $s1, $s2 ) );
}

function get_application_index_page () {
 $index = 'index.php';
 $url = application_url ( 'application_index.php/pass' );

 if ( ! preg_match ( '/\.[a-zA-Z]*$/', $_SERVER [ 'HTTP_HOST' ] ) ) {
 $url = str_replace ( '://' . $_SERVER [ 'HTTP_HOST' ] . '/', '://' . @gethostbyname ( $_SERVER [ 'HTTP_HOST' ] ) . '/', $url );
 }

 $status = http_get ( $url );
 if ( $status != 'true' ) {
 return $index . '?';
 }
 else {
 return $index;
 }
}

function get_domain_name () {
 $kt = parse_url ( application_url () );
 return $kt [ 'host' ];
}

function http_get ( $url, $_get = array () ) {
 $_query = NULL;
 $contents = NULL;

 if ( ! empty ( $_get ) ) {
 $_query = '?';

 foreach ( $_get as $key => $value ) {
 $_query .= $key . '=' . $value . '&amp;';
 }

 $_query = rtrim ( $_query, '&amp;' );
 }

 if ( ini_get ( 'allow_url_fopen' ) == "1" ) {

 $handle = @fopen ( $url . $_query, "r" );
 if ( $handle === FALSE ) {
 return $handle;
 }

 while ( ! feof ( $handle ) ) {
 $contents .= fread ( $handle, 8192 );
 }
 fclose ( $handle );
 }
 else {
 include_once ( 'HttpClient.php' );
 $contents = HttpClient::quickGet ( $url . $_query );
 }

 return trim ( $contents );
}

function __button ( $text, $color = '', $action_type = '', $text_color = 'FFFFFF', $font = 'AlteHaasGroteskBold', $size = 10, $type = 'submit', $params = array () ) {
 $add_params = '';
 if ( ! empty ( $params ) ) {
 foreach ( $params as $k => $v ) {
 $add_params .= "$k=\"$v\" ";
 }
 }

 return '<button type="' . $type . '" ' . trim ( $add_params ) . '>
 <span>
 <i></i>
 <p>'
. $text . '<em style="color:#' . $text_color . '!important">' . $text . '</em></p>
 </span>
 <b></b>
 </button>'
;
}

function __img_text ( $text, $text_color = 'FFFFFF', $font = 'AlteHaasGroteskBold', $size = 10 ) {
 return '<img src="' . @preg_replace ( '@install/@', '', application_url () ) . 'scripts/buttons.php?text=' . base64_encode ( $text ) . '&amp;size=' . $size . '&amp;font=' . $font . '&amp;color=' . $text_color . '" />';
}

function get_application_folder () {
 $http_host = $_SERVER [ 'HTTP_HOST' ];
 $url = application_url ();

 if ( $http_host == '' ) {
 $http_host = $_SERVER [ 'SERVER_NAME' ];
 }

 $kt = explode ( $http_host, $url );

 if ( isset ( $kt [ 1 ] ) ) {
 if ( str_replace ( 'install/', '', $kt [ 1 ] ) != '' ) {
 return add_start_end_slashes ( str_replace ( 'install/', '', $kt [ 1 ] ) );
 }
 }
 return '';
}

function ws_read_file ( $file ) {
 if ( ! file_exists ( $file ) ) {
 return FALSE;
 }

 if ( function_exists ( 'file_get_contents' ) ) {
 return file_get_contents ( $file );
 }

 if ( ! $fp = @fopen ( $file, FOPEN_READ ) ) {
 return FALSE;
 }

 flock ( $fp, LOCK_SH );

 $data = '';
 if ( filesize ( $file ) > 0 ) {
 $data = &amp; fread ( $fp, filesize ( $file ) );
 }

 flock ( $fp, LOCK_UN );
 fclose ( $fp );

 return $data;
}

function create_config_file () {
 global $form_validation;
 if ( array_key_exists ( 'HOSTNAME', $_POST ) ) {
 extract ( $_POST );

 $form_validation->add_field ( 'HOSTNAME', 'required', Lang ( 'required' ) );
 $form_validation->add_field ( 'DATABASE', 'required', Lang ( 'required' ) );
 $form_validation->add_field ( 'DBUSER', 'required', Lang ( 'required' ) );

 $form_validation->add_field ( 'ADMIN_EMAIL', 'valid_email', Lang ( 'valid_email' ) );
 $form_validation->add_field ( 'SITE_NAME', 'required', Lang ( 'required' ) );
 $form_validation->add_field ( 'SITE_SLOGAN', 'required', Lang ( 'required' ) );

 if ( $form_validation->execute () ) {
 @$db_link = @mysql_connect ( $HOSTNAME, $DBUSER, $DBPASS );

 if ( $db_link ) {
 @mysql_select_db ( $DATABASE );
 }
 else {
 return sprintf ( "Invalid database parameters. Details (if any):<br />%s", @mysql_error () );
 }

 $schema = ws_read_file ( "schema.txt" );
 $schema = str_replace ( '{|DBPREFIX|}', $DBPREFIX, $schema );
 $schema = str_replace ( '{|ADMIN_USERNAME|}', $DEFAULT_USERNAME, $schema );
 $schema = str_replace ( '{|ADMIN_PASSWORD|}', md5 ( $DEFAULT_PASSWORD ), $schema );
 $schema = str_replace ( '{|NOW|}', time (), $schema );
 $schema = str_replace ( '{|ADMIN_EMAIL|}', $ADMIN_EMAIL, $schema );

 $schema_kt = preg_split ( '/;[\n\r]+/', $schema );

 foreach ( $schema_kt as $schema_query ) {
 if ( ! @mysql_query ( $schema_query ) ) {
 return sprintf ( "I failed to setup your database. Please make sure you provided the right mysql credentials!<br /><br />Details (if any):<br />%s", @mysql_error () );
 }
 }

 if ( $db_link ) {
 @mysql_close ( $db_link );
 }

 $settings = array ();
 $settings [ 'HOSTNAME' ] = prepare_constant ( $_POST [ 'HOSTNAME' ] );
 $settings [ 'DATABASE' ] = prepare_constant ( $_POST [ 'DATABASE' ] );
 $settings [ 'DBUSER' ] = prepare_constant ( $_POST [ 'DBUSER' ] );
 $settings [ 'DBPASS' ] = prepare_constant ( $_POST [ 'DBPASS' ] );
 $settings [ 'DBPREFIX' ] = prepare_constant ( $_POST [ 'DBPREFIX' ] );
 $settings [ 'SECURITY_KEY' ] = prepare_constant ( md5 ( print_unique_id () ) );
 $settings [ 'APPLICATION_URL' ] = prepare_constant ( add_ending_slash ( str_replace ( 'install/', '', application_url () ) ) );
 $settings [ 'APPLICATION_INDEX_PAGE' ] = prepare_constant ( get_application_index_page () );
 $settings [ 'ADMIN_EMAIL' ] = prepare_constant ( $_POST [ 'ADMIN_EMAIL' ] );
 $settings [ 'DOMAIN_NAME' ] = prepare_constant ( get_domain_name () );
 $settings [ 'SITE_NAME' ] = prepare_constant ( $_POST [ 'SITE_NAME' ] );
 $settings [ 'SITE_SLOGAN' ] = prepare_constant ( $_POST [ 'SITE_SLOGAN' ] );
 $settings [ 'USE_SMTP' ] = prepare_constant ( "0", TRUE );

 $settings [ 'SMTP_PORT' ] = prepare_constant ( "" );
 $settings [ 'SMTP_HOST' ] = prepare_constant ( "" );
 $settings [ 'SMTP_USER' ] = prepare_constant ( "" );
 $settings [ 'SMTP_PASS' ] = prepare_constant ( "" );

 $settings [ 'MAIL_IS_HTML' ] = prepare_constant ( "1", TRUE );
 $settings [ 'APPLICATION_FOLDER' ] = prepare_constant ( get_application_folder () );
 $settings [ 'REDIRECT_TO_LOGIN' ] = prepare_constant ( "login" );
 $settings [ 'REDIRECT_AFTER_LOGIN' ] = prepare_constant ( "members" );
 $settings [ 'REDIRECT_ON_LOGOUT' ] = prepare_constant ( "login" );
 $settings [ 'RUN_ON_DEVELOPMENT' ] = prepare_constant ( "0", TRUE );
 $settings [ 'TOOLTIPS_ENABLED' ] = prepare_constant ( "1", TRUE );
 $settings [ 'REDIRECT_AFTER_CONFIRMATION' ] = prepare_constant ( "1", TRUE );
 $settings [ 'ALLOW_USERNAME_CHANGE' ] = prepare_constant ( "0", TRUE );
 $settings [ 'DEFAULT_EMAIL_TEMPLATE' ] = prepare_constant ( "default" );
 $settings [ 'KEEP_LOGGED_IN_FOR' ] = 60 * 60 * 24 * 100;
 $settings [ 'ALLOW_REMEMBER_ME' ] = prepare_constant ( "1", TRUE );
 $settings [ 'LANG_TYPE' ] = prepare_constant ( "english" );
 $settings [ 'ENABLE_MOD_REWRITE' ] = prepare_constant ( "1", TRUE );
 $settings [ 'DEFAULT_TEMPLATE' ] = prepare_constant ( "default" );
 $settings [ 'MIN_USR_VOTES_HOMEPAGE' ] = 5;
 $settings [ 'MIN_WALL_VOTES_HOMEPAGE' ] = 3;
 $settings [ 'WALLPAPER_DISPLAY_ORDER' ] = prepare_constant ( "date_added" );
 $settings [ 'WALLPAPER_ORDER_TYPE' ] = prepare_constant ( "DESC" );
 $settings [ 'MAX_TAGS' ] = prepare_constant ( 20 );
 $settings [ 'TAGS_ORDER_BY' ] = prepare_constant ( "" );
 $settings [ 'TAGS_ORDER_BY_METHOD' ] = prepare_constant ( "" );
 $settings [ 'TAGS_MIN_CHARACTERS' ] = prepare_constant ( 3 );
 $settings [ 'CATEGORY_COLUMNS' ] = prepare_constant ( 3 );
 $settings [ 'SHOW_CATEGORY_COUNTERS' ] = prepare_constant ( "0", TRUE );
 $settings [ 'TRACKING_CODE' ] = prepare_constant ( "" );
 $settings [ 'AD_CODE' ] = prepare_constant ( "" );
 $settings [ 'TOP_DOWNLOAD_AD_CODE' ] = prepare_constant ( "" );
 $settings [ 'WALLPAPER_AD_CODE' ] = prepare_constant ( "" );
 $settings [ 'WALLPAPER_IPHONE_AD_CODE' ] = prepare_constant ( "" );
 $settings [ 'WALLPAPER_DOWNLOAD_AD_CODE' ] = prepare_constant ( "" );
 $settings [ 'ENABLE_MOD_REWRITE' ] = prepare_constant ( "0", TRUE );
 $settings [ 'WALLPAPER_QUALITY' ] = prepare_constant ( 100 );
 $settings [ 'WALLPAPERS_PER_COLUMN' ] = prepare_constant ( 6 );
 $settings [ 'SITE_HAS_ADULT_MATERIALS' ] = prepare_constant ( "0", TRUE );
 $settings [ 'GUESTS_CAN_DOWNLOAD' ] = prepare_constant ( "1", TRUE );
 $settings [ 'GUESTS_CAN_UPLOAD' ] = prepare_constant ( "1", TRUE );
 $settings [ 'AUTO_APROVE_COMMENTS' ] = prepare_constant ( "0", TRUE );
 $settings [ 'OPEN_WALLPAPERS_IN_NEW_WINDOW' ] = prepare_constant ( "1", TRUE );
 $settings [ 'MAX_COLORS' ] = prepare_constant ( 162 );

 $files_settings = new WS_Settings_writer ( );
 $files_settings->Set ( 'Settings', $settings );
 $files_settings->ConfigFile = '../settings.php';

 if ( $files_settings->Save () ) {
 header ( "Refresh:0;url=../index.php" );
 }
 else {
 return 'Settings not saved. Please check your fields for errors and also that you applied the right permissions to all required files and folders.';
 }
 }
 }
}
//END

&amp;nbsp;

Free PHP script For SQL FAQ

Simply upload the Free PHP / SQL FAQ files to a directory on your PHP enabled server, edit the included file Local_Settings.php and enter in the relevant info for your site, including your database connection info. Then run the SQL Table Creator script, and your FAQ system is now ready to use. You can configure the look and feel of your new Free PHP / SQL FAQ via a number of methods.You can choose an alternate .CSS file (in the Local_Settings.php file) to change between looks of your site. Alternatively you can edit the active .CSS file to change specific elements, color schemes and other visual properties. Also, the script package contains two files, a Header.php and Footer.php file that are included in every visable page. They are a good place to add site logos and links to help the pages fit seamlessly into your site’s main design and navigation. Finally, if you are PHP savvy, you can edit the actual codes and functions in the Free PHP / SQL FAQ, taking complete control.

 

 

//////////////////////////////////////////////////////////////////////
// The freebert.com PHP/SQL Frequently Asked Questions (FAQ) Script:
// Version 0.41 - December 1, 2007
// Free to use, edit &amp; customize, so long as the freebert.com logo,
// the 'Powered By The Free PHP SQL FAQ Script' text &amp; links
// remain displayed on the bottom of every visable page.
// Redistribution in whole or in part of any page or function within
// the freebert.com PHP/SQL Frequently Asked Questions Script is strictly forbidden
// without the express written consent from freebert.com.
// Copyright (c) December 2007 by Colin Burke - freebert.com
// Contact: support@freebert.com
// Support: http://www.freebert.com/Wiki/index.php/FPHPFAQ
//////////////////////////////////////////////////////////////////////

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

The freebert.com PHP/SQL Frequently Asked Questions (FAQ) Script Offical READ_ME.txt
Version 0.41 - December 1, 2007

Contents:
1) - License Info
2) - Minimum Requirements
3) - Downloading the latest version of the PHP/SQL FAQ Script
4) - Uploading the PHP/SQL FAQ Script to your server
5) - Configuring The PHP/SQL FAQ Script to run on your server
 a) - Local Settings
 b) - Installing Database Tables
6) - Customizing The PHP/SQL FAQ Script to better match your site's look &amp; style
7) - Managing FAQ Entries:
 a) Logging In To The Admin Area
 b) Adding A New FAQ Entry
 c) Editing An Existing FAQ Entry
 d) Deleting An Existing FAQ Entry
 e) Changing The Order That FAQ Entries Are Displayed
8) - Additional Support

1) - License Info
The freebert PHP/SQL Frequently Asked Questions (FAQ) Script package is free to use, with the condition that regardless of any changes you make to the code, you keep the FreeBert '
FB' link and logo visible on the bottom of every page within the package. You are forbidden from reselling and / or redistributing the freebert PHP/SQL Frequently Asked Questions (FAQ) Script package in whole or part without express written permission from freebert.com.

2) - Minimum Requirements
The freebert PHP/SQL Frequently Asked Questions (FAQ) Script only requires:
- A PHP enabled server with access to session variables activated. Most PHP servers are configured to allow the use of session variables.
- Access to a web hosted SQL database. Most hosting packages include access to an SQL database.
Tip: If you are not sure if your PHP server is configured to allow the use of session variables, or if you have access to an SQL database, please contact your server administrator / hoster.

3) - Downloading the latest version of the PHP/SQL FAQ Script
Make sure you have the very latest version of the Free PHP/SQL FAQ - you can check the latest version available at:
http://www.freebert.com/Products/PHPSQLFAQScript/
If you do not have the most up to date version of the Free PHP/SQL FAQ, you can download it from that same page.

4) - Uploading the PHP/SQL FAQ Script to your server
Once you have downloaded and unzipped your copy of the PHP/SQL FAQ Script, you need to upload it to your server.  Create a directory on your server for the PHP/SQL FAQ Script pages to go (usually in the root directory of your site domain)  For example, you could create a subdirectory called PHPSQLFAQ on your root directory, which in the URL box of a browser would result in: http://www.youdomain.com/PHPSQLFAQ/
Keep track of what directory you upload to ('
/PHPSQLFAQ/' in the above example), you will need that when configuring the package on your server.

5) - Configuring The PHP/SQL FAQ Script to run on your server
Once you have uploaded all the PHP/SQL FAQ Script files to a directory on your web server, you are ready to configure the package to run on your server.  To do so, you will need to edit the Local_Settings.php file in the faq script'
s root directory (if you uploaded your faq files to http://www.youdomain.com/PHPSQLFAQ/, the script root directory would be '/PHPSQLFAQ/').  In the Local_Settings.php file, you will see there are several settings that can be set, grouped into a couple of sections.

a) - Local Settings - The Local_Settings.php file stores info about your site required by the script and relate to the general setup of your faq script:
$Site_Domain - this should be the full domain of the root of your site
Example: 'http://www.freebert.com/'
Tip: be sure to end your domain with a '/'
$Site_Title - self explanatory
$Site_Script_Root_Directory - the name of the directory the script files reside in.
Example: if you uploaded the script files to http://www.youdomain.com/PHPSQLFAQ/, set Site_Script_Root_Directory = 'PHPSQLFAQ/'
Tip: be sure to end your Site_Script_Root_Directory with a '/'
$CSS_Filename - the name of the CSS file you want the script to use.  Enter the title of the file only, and be sure that that file exists in the /css/ folder in your script directory.  The package includes 2 default CSS files in the css directory, called WhiteBack.css and BlackBack.css.  Try switching between these two to change the basic color scheme of your site.
$Admin_Username="admin" - username used to login to secure admin section - we suggest changing from default 'admin' upon installation
$Admin_Password="admin" - password used to login to secure admin section - we suggest changing from default 'admin' upon installation
$FBFAQ_DB_S = "sqlc1.megasqlservers.com" - The server / IP address of your mysql server
$FBFAQ_DB_U = "casinobunn862977" - The account username for your mysql server
$FBFAQ_DB_P = "opendoors" - The account password for your mysql server
$FBFAQ_DB_DB = "L10stats_casinobunny_com" - The name of the database in your mysql server
$FBFAQ_DB_Prefix = "FBFAQ_" - a prefix for use on the tables created by the script - leave as is after you have created your database tables

b) - Installing Database Tables - Once you have uploaded the package files to your server, and have added your specific info to the Local_Settings.php file (including your SQL Database info), you are ready to create the required tables in your SQL database.  You have two methods to do this: run our table creation page, or manually create the tables in your database.
i - To install the tables to your database using our premade script, run the InstallTables.php file located in the root directory of your uploaded package files.  You must have already configured your database connection info in the Local Settings file for the installation script to work.
ii - To install the tables to your database manually, either copy and paste or manually setup the SQL tables using the info below:
*note:
(in the examples below, replace ".$Table_Prefix." - including the "" quotes - with the value you have set in your Local Settings file for database prefix.)

CREATE TABLE `".$Table_Prefix."Answers` (
 `Answer_ID` int(10) unsigned NOT NULL auto_increment,
 `Question_ID` int(5) unsigned default NULL,
 `Answer_Text` text,
 PRIMARY KEY  (`Answer_ID`),
 UNIQUE KEY `Answer_ID` (`Answer_ID`),
 KEY `Answer_ID_2` (`Answer_ID`)
 )

CREATE TABLE `".$Table_Prefix."Questions` (
 `Question_ID` int(5) unsigned NOT NULL auto_increment,
 `Question_Title` varchar(255) default NULL,
 `Question_Priority` int(10) unsigned default NULL,
 PRIMARY KEY  (`Question_ID`),
 UNIQUE KEY `Question_ID` (`Question_ID`),
 KEY `Question_ID_2` (`Question_ID`)
 )


6) - Customizing The PHP/SQL FAQ Script to better match your site's look &amp; style.
There are a number of ways you can customize the look of your PHP/SQL FAQ Script, to better blend the faq pages in the basic look &amp; style of the rest of your site.  Firstly, you can choose an alternate .CSS file (in the Local_Settings.php file) to change between looks of your site. Alternatively you can edit the active .CSS file to change specific elements, color schemes and other visual properties. The faq package contains two files, Overall_Header.php and Overall_Footer.php (located in the script'
s /inc/skin/ directory) that are included in every visible faq page. They are a good place to add site logos and links to help the faq fit seamlessly into your site's main design. Finally, if you are PHP savvy, you can edit the actual codes and functions in the faq pages, taking complete control of the look, feel and function of your faq.  Be careful if/when editing PHP pages - a single misplaced quote or semi-colon could stop the functioning of your entire faq!

7) - Managing FAQ Entries:
a) Logging In To The Admin Area
To make adding, editing, deleting and reorganizing your FAQ entries as easy as possible, we have included a secured admin section where you can manage all FAQ contents.
To login to your admin script section, be sure you have already edit your Local Settings file, and have created the required tables in the database (see above).  Login to the admin section by opening in your browser FPHPFAQ/admin/Login.php.  The admin login and password are stored in the Local Settings file, and are both '
admin' (without the quotes) by default.  Enter the admin login and password that are saved in the Local Settings file.

b) - Adding A New FAQ Entry
Adding a new FAQ Entry is very easy.  Once logged in to the FPHPFAQ admin section on your site, click the Add New FAQ Entry button to view the add Entry Form.  Fill out the form by entering the FAQ question (or title) and the answer (main text body).  Click the submit button to save your data and create your new entry.

c) - Editing An Existing FAQ Entry
To edit an existing FAQ entry, click on the '
Edit' button beside the title of the entry you want to edit in the Admin section of your FPHPFAQ.  The Edit entry form allows you to edit the existing question and answer text and save the changes.

d) - Deleting An Existing FAQ Entry
To delete an existing FAQ entry, click on the '
Delete' button beside the title of the entry you want to delete in the Admin section of your FPHPFAQ.  Your entry will be deleted permanently, so be carefull.

e) - Changing The Order That FAQ Entries Are Displayed
To change the order that your FAQ entries are displayed, click the '
+' or '-' buttons beside the title of the entry you want to move in the Admin section of your FPHPFAQ.  Your entries will be updated instantly.

8) - Additional Support
Additional support for the freebert.com Free PHP SQL FAQ can be found in the freebert.com Support Wiki:
http://www.freebert.com/Wiki/index.php/FPHPFAQ

//////////////////////////////////////////////////////////////////////
// The freebert.com PHP/SQL Frequently Asked Questions (FAQ) Script:
// Version 0.41 - December 1, 2007
// Free to use, edit &amp; customize, so long as the freebert.com logo,
// the '
Powered By The Free PHP SQL FAQ Script' text &amp; links
// remain displayed on the bottom of every visable page.
// Redistribution in whole or in part of any page or function within
// the freebert.com PHP/SQL Frequently Asked Questions Script is strictly forbidden
// without the express written consent from freebert.com.
// Copyright (c) December 2007 by Colin Burke - freebert.com
// Contact: support@freebert.com
// Support: http://www.freebert.com/Wiki/index.php/FPHPFAQ
//////////////////////////////////////////////////////////////////////

&amp;nbsp;

&amp;nbsp;

PHP Hav­ing prob­lems installing w-scrips

First of all, down­load lat­est w-script ver­sion, there should be large green but­ton some­where in this page. Unzip the package.Fire up your favorite FTP client, if you don’t have one, I’d sug­gest using FileZilla, install and usage instruc­tions are on their site. Upload all the files from folder wscript to your host. The uplouad takes a few min­utes, so mean­while go to your host’s CPanel (usu­ally yourdomain.com/cpanel) Find the sec­tion Data­bases there and click on MySQL® Data­base wizard.

 

 

<?php
 error_reporting ( E_WARNING );

 define ( "MODULES_DIR", '../' . realpath ( dirname ( __FILE__ ) ) . '/system/application/modules/' );
 define( "ADMIN_EMAIL", "" );
 include ( "form_validation.php" );
 include ( "../system/application/libraries/ws_settings_writer.php" );
 include "install.functions.php";
 $form_validation     = new Form_validation ();

 $error = FALSE;

 if ( Verify_files_before_install () !== TRUE ) {
 $error = Verify_files_before_install ();
 }
 else {
 $error = create_config_file ();
 }

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>W-script Installation</title>
 <link href="../templates/default/css/reset.css" rel="stylesheet" type="text/css" />
 <link href="../templates/default/css/default.css" rel="stylesheet" type="text/css" />
 <link href="../templates/default/css/forms.css" rel="stylesheet" type="text/css" />
 <link href="css/buttons.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="../templates/default/js/jquery132.js"></script>
 <script type="text/javascript" src="../templates/default/js/jquery-ui-171.js"></script>
 <script type="text/javascript">
 jQuery(document).ready ( function () {
 setTimeout
 (
 load_installer,
 1000
 );
 });

 function load_installer () {
 $( '#installer_main' ).show ( 'slow' );
 }
 </script>
 <style type="text/css">
 form.appnitro li {width:99%!important;padding-top:8px}
 form.appnitro li h3 {padding:0!important;text-align:center;}
 form.appnitro li h3, h1 {border:none!important}
 </style>
</head>

<body style="background-image:none!important;background-color:#383939!important;">
<!-- MENU -->
<center style="margin:60px auto;width:800px;background:transparent url('../templates/default/images/ajax-loader.gif') no-repeat 50% 50%;min-height:500px">
 <div id="installer_main" style="display:none;text-align:left">
 <h1 style="text-align:center;font-family:verdana,arial;color:#ccc;font-size:14px"><img src="img/ws.png" /></h1>
 <form method="post">
 <fieldset style="background: #555;padding:15px 35px 10px 15px;border:4px solid #000!important;-moz-border-radius: 10px;-webkit-border-radius: 10px;border-radius: 10px;">
<?php
 if ( $error != FALSE ) {
 echo '<p>' . $error . '</p>';
 }
?>
 <input name="USE_SMTP" type="hidden" id="USE_SMTP" value="0" />
 <input name="MAIL_IS_HTML" type="hidden" id="MAIL_IS_HTML" value="1" />
 <ul style="width:49%;float:left">
 <!-- ==================================    DATABASE ============================= -->
 <li>
 <h3><img src="img/ds.png" /></h3>
 </li>
 <li>

 <label for="HOSTNAME">Hostname:</label>
 <div align="left">
 <input name="HOSTNAME" type="text" id="HOSTNAME" value="<?= $form_validation->getField_value ( 'HOSTNAME', 'localhost' ) ?>" />
 <?=$form_validation->printField_error ( 'HOSTNAME' )?>
 </div>
 </li>

 <li>
 <label for="DATABASE">Database Name:</label>
 <div align="left">
 <input name="DATABASE" type="text" id="DATABASE" value="<?= $form_validation->getField_value ( 'DATABASE' ) ?>" />
 <?=$form_validation->printField_error ( 'DATABASE' )?>
 </div>
 </li>

 <li>
 <label for="DBUSER">Database User:</label>
 <div align="left">
 <input name="DBUSER" type="text" id="DBUSER" value="<?= $form_validation->getField_value ( 'DBUSER' ) ?>" />
 <?=$form_validation->printField_error ( 'DBUSER' )?>
 </div>
 </li>

 <li>
 <label for="DBPASS">Database Password:</label>
 <div align="left">
 <input name="DBPASS" type="password" id="DBPASS" value="<?= $form_validation->getField_value ( 'DBPASS' ) ?>" />
 <?=$form_validation->printField_error ( 'DBPASS' )?>
 </div>
 </li>

 <li>
 <label for="DBPREFIX">Database Prefix:</label>
 <div align="left">
 <input name="DBPREFIX" type="text" id="DBPREFIX" value="<?= $form_validation->getField_value ( 'DBPREFIX', 'wscript_' ) ?>" />
 <?=$form_validation->printField_error ( 'DBPREFIX' )?>
 </div>
 </li>
 </ul>

 <!-- ==================================    SITE SETTINGS ============================= -->
 <ul style="width:49%;float:right">
 <li>
 <h3><img src="img/gs.png" /></h3>
 </li>

 <li>

 <label for="DEFAULT_USERNAME">Admin Username:</label>
 <div align="left">
 <input name="DEFAULT_USERNAME" type="text" id="DEFAULT_USERNAME" value="<?= $form_validation->getField_value ( 'DEFAULT_USERNAME' ) ?>" />
 <?=$form_validation->printField_error ( 'DEFAULT_USERNAME' )?>
 </div>
 </li>
 <li>

 <label for="DEFAULT_PASSWORD">Admin Password:</label>
 <div align="left">
 <input name="DEFAULT_PASSWORD" type="password" id="DEFAULT_PASSWORD" value="<?= $form_validation->getField_value ( 'DEFAULT_PASSWORD' ) ?>" />
 <?=$form_validation->printField_error ( 'DEFAULT_PASSWORD' )?>
 </div>
 </li>

 <li>
 <label for="ADMIN_EMAIL">Admin Email:</label>
 <div align="left">
 <input name="ADMIN_EMAIL" type="text" id="ADMIN_EMAIL" value="<?= $form_validation->getField_value ( 'ADMIN_EMAIL' ) ?>" />
 <?=$form_validation->printField_error ( 'ADMIN_EMAIL' )?>
 </div>
 </li>

 <li>
 <label for="SITE_NAME">Site Name:</label>
 <div align="left">
 <input name="SITE_NAME" type="text" id="SITE_NAME" value="<?= $form_validation->getField_value ( 'SITE_NAME' ) ?>" />
 <?=$form_validation->printField_error ( 'SITE_NAME' )?>
 </div>
 </li>

 <li>
 <label for="SITE_SLOGAN">Site Slogan:</label>
 <div align="left">
 <input name="SITE_SLOGAN" type="text" id="SITE_SLOGAN" value="<?= $form_validation->getField_value ( 'SITE_SLOGAN' ) ?>" />
 <?=$form_validation->printField_error ( 'SITE_SLOGAN' )?>
 </div>
 </li>
 </ul>
<div></div>
 <ul>
 <li style="padding-top:20px">
 <?= __button ( 'Perform Installation' ) ?>
 </li>
 </ul>
 </fieldset>
 </form>

 <div></div>
 </div>
 <!-- FOOTER -->
</center>
</body>

</html>

&amp;nbsp;

Scripts friendly urls without mod_rewrite

The previous tutorials in the Apaches mod_rewrite series covered how to enable mod_rewrite on apache and how to use mod_rewrite for search engine friendly urls. This tutorial will not cover how to get search engine friendly urls with using mod_rewrite, but how to do the same using php and apache filesmatch instead of mod_rewrite.

 

 

<?php
// Pre-2.6 compatibility
if( !defined('WP_CONTENT_DIR') )
 define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' );

if( !include( WP_CONTENT_DIR . '/wp-cache-config.php' ) )
 return;
if( !defined( 'WPCACHEHOME' ) )
 define('WPCACHEHOME', dirname(__FILE__).'/');

include( WPCACHEHOME . 'wp-cache-base.php');

if(defined('DOING_CRON')) {
 require_once( WPCACHEHOME . 'wp-cache-phase2.php');
 return;
}

$mutex_filename = 'wp_cache_mutex.lock';
$new_cache = false;


// Don't change variables behind this point

$plugins = glob( WPCACHEHOME . 'plugins/*.php' );
if( is_array( $plugins ) ) {
 foreach ( $plugins as $plugin ) {
 if( is_file( $plugin ) )
 require_once( $plugin );
 }
}

if (!$cache_enabled || $_SERVER["REQUEST_METHOD"] == 'POST')
 return;

$file_expired = false;
$cache_filename = '';
$meta_file = '';
$wp_cache_gzip_encoding = '';

function gzip_accepted(){
 if( ini_get( 'zlib.output_compression' ) ) // don't compress WP-Cache data files when PHP is already doing it
 return false;

 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === false) return false;
 return 'gzip';
}

if ($cache_compression) {
 $wp_cache_gzip_encoding = gzip_accepted();
}

$key = $blogcacheid . md5($_SERVER['HTTP_HOST'].preg_replace('/#.*$/', '', str_replace( '/index.php', '/', $_SERVER['REQUEST_URI'] ) ).$wp_cache_gzip_encoding.wp_cache_get_cookies_values());

$cache_filename = $file_prefix . $key . '.html';
$meta_file = $file_prefix . $key . '.meta';
$cache_file = realpath( $cache_path . $cache_filename );
$meta_pathname = realpath( $cache_path . 'meta/' . $meta_file );

$wp_start_time = microtime();
if( ($mtime = @filemtime($meta_pathname)) ) {
 if ($mtime + $cache_max_time > time() ) {
 $meta = new CacheMeta;
 if (! ($meta = unserialize(@file_get_contents($meta_pathname))) )
 return;
 foreach ($meta->headers as $header) {
 // godaddy fix, via http://blog.gneu.org/2008/05/wp-supercache-on-godaddy/ and http://www.littleredrails.com/blog/2007/09/08/using-wp-cache-on-godaddy-500-error/
 if( strpos( $header, 'Last-Modified:' ) === false )
 header($header);
 }
 if ( !($content_size = @filesize($cache_file)) > 0 || $mtime < @filemtime($cache_file))
 return;
 if ($meta->dynamic) {
 include($cache_file);
 } else {
 /* No used to avoid problems with some PHP installations
 $content_size += strlen($log);
 header("Content-Length: $content_size");
 */

 if(!@readfile ($cache_file))
 return;
 }
 die;
 }
 $file_expired = true; // To signal this file was expired
}

function wp_cache_postload() {
 global $cache_enabled;

 if (!$cache_enabled)
 return;
 require_once( WPCACHEHOME . 'wp-cache-phase2.php');
 wp_cache_phase2();
}

function wp_cache_get_cookies_values() {
 $string = '';
 while ($key = key($_COOKIE)) {
 if (preg_match("/^wp-postpass|^wordpress|^comment_author_/", $key)) {
 $string .= $_COOKIE[$key] . ",";
 }
 next($_COOKIE);
 }
 reset($_COOKIE);

 // If you use this hook, make sure you update your .htaccess rules with the same conditions
 $string = do_cacheaction( 'wp_cache_get_cookies_values', $string );
 return $string;
}

function add_cacheaction( $action, $func ) {
 global $wp_supercache_actions;
 $wp_supercache_actions[ $action ][] = $func;
}

function do_cacheaction( $action, $value = '' ) {
 global $wp_supercache_actions;
 if( is_array( $wp_supercache_actions[ $action ] ) ) {
 $actions = $wp_supercache_actions[ $action ];
 foreach( $actions as $func ) {
 $value = $func( $value );
 }
 }

 return $value;
}

?>

&amp;nbsp;

Mod_Rewrite URLs for Search Engines

This tutorial will teach you how to use Apache Mod_Rewrite engine to manipulate urls of your website, so that your site can increase hits from search engines.

 

 

<?php
$known_headers = array("Last-Modified", "Expires", "Content-Type", "Content-type", "X-Pingback", "ETag", "Cache-Control", "Pragma");

if (!class_exists('CacheMeta')) {
 class CacheMeta {
 var $dynamic = false;
 var $headers = array();
 var $uri = '';
 var $post = 0;
 }
}

?>

&amp;nbsp;

PHP Using mod_rewrite To Your Advantage

Learn how to use mod_rewrite to your advantage to take some overhead off your PHP script and validate Query Strings faster and more securely than any hard coded PHP script.

 

 

<?php

function wp_cache_phase2() {
 global $cache_filename, $cache_acceptable_files, $wp_cache_meta_object, $wp_cache_gzip_encoding, $super_cache_enabled, $cache_rebuild_files;

 wp_cache_mutex_init();
 if(function_exists('add_action') &amp;&amp; ( !defined( 'WPLOCKDOWN' ) || ( defined( 'WPLOCKDOWN' ) &amp;&amp; constant( 'WPLOCKDOWN' ) == '0' ) ) ) {
 // Post ID is received
 add_action('publish_post', 'wp_cache_post_edit', 0);
 add_action('edit_post', 'wp_cache_post_change', 0); // leaving a comment called edit_post
 add_action('delete_post', 'wp_cache_post_edit', 0);
 add_action('publish_phone', 'wp_cache_post_edit', 0);
 // Coment ID is received
 add_action('trackback_post', 'wp_cache_get_postid_from_comment', 0);
 add_action('pingback_post', 'wp_cache_get_postid_from_comment', 0);
 add_action('comment_post', 'wp_cache_get_postid_from_comment', 0);
 add_action('edit_comment', 'wp_cache_get_postid_from_comment', 0);
 add_action('wp_set_comment_status', 'wp_cache_get_postid_from_comment', 0);
 // No post_id is available
 add_action('delete_comment', 'wp_cache_no_postid', 0);
 add_action('switch_theme', 'wp_cache_no_postid', 0);

 add_action('wp_cache_gc','wp_cache_gc_cron');

 do_cacheaction( 'add_cacheaction' );
 }
 if( $_SERVER["REQUEST_METHOD"] == 'POST' || get_option('gzipcompression'))
 return;
 $script = basename($_SERVER['PHP_SELF']);
 if (!in_array($script, $cache_acceptable_files) &amp;&amp;
 wp_cache_is_rejected($_SERVER["REQUEST_URI"]))
 return;
 if (wp_cache_user_agent_is_rejected()) return;
 $wp_cache_meta_object = new CacheMeta;
 if($wp_cache_gzip_encoding)
 header('Vary: Accept-Encoding, Cookie');
 else
 header('Vary: Cookie');
 ob_start('wp_cache_ob_callback');

 // restore old supercache file temporarily
 if( $super_cache_enabled &amp;&amp; $cache_rebuild_files ) {
 $user_info = wp_cache_get_cookies_values();
 $do_cache = apply_filters( 'do_createsupercache', $user_info );
 if( $user_info == '' || $do_cache === true ) {
 $dir = get_current_url_supercache_dir();
 $files_to_check = array( $dir . 'index.html', $dir . 'index.html.gz' );
 foreach( $files_to_check as $cache_file ) {
 if( !file_exists( $cache_file . '.needs-rebuild' ) )
 continue;
 $mtime = @filemtime($cache_file . '.needs-rebuild');
 if( $mtime &amp;&amp; (time() - $mtime) < 30 ) {
 @rename( $cache_file . '.needs-rebuild', $cache_file );
 }
 // cleanup old files or if rename fails
 if( @file_exists( $cache_file . '.needs-rebuild' ) ) {
 @unlink( $cache_file . '.needs-rebuild' );
 }
 }
 }
 }
 register_shutdown_function('wp_cache_shutdown_callback');
}

function wp_cache_get_response_headers() {
 if(function_exists('apache_response_headers')) {
 flush();
 $headers = apache_response_headers();
 } else if(function_exists('headers_list')) {
 $headers = array();
 foreach(headers_list() as $hdr) {
 list($header_name, $header_value) = explode(': ', $hdr, 2);
 $headers[$header_name] = $header_value;
 }
 } else
 $headers = null;

 return $headers;
}

function wp_cache_is_rejected($uri) {
 global $cache_rejected_uri;

 if (strstr($uri, '/wp-admin/'))
 return true; // we don't allow caching of wp-admin for security reasons
 foreach ($cache_rejected_uri as $expr) {
 if( preg_match( "~$expr~", $uri ) )
 return true;
 }
 return false;
}

function wp_cache_user_agent_is_rejected() {
 global $cache_rejected_user_agent;

 if (!function_exists('apache_request_headers')) return false;
 $headers = apache_request_headers();
 if (!isset($headers["User-Agent"])) return false;
 foreach ($cache_rejected_user_agent as $expr) {
 if (strlen($expr) > 0 &amp;&amp; stristr($headers["User-Agent"], $expr))
 return true;
 }
 return false;
}


function wp_cache_mutex_init() {
 global $use_flock, $mutex, $cache_path, $mutex_filename, $sem_id;

 if(!is_bool($use_flock)) {
 if(function_exists('sem_get'))
 $use_flock = false;
 else
 $use_flock = true;
 }

 $mutex = false;
 if ($use_flock)
 $mutex = @fopen($cache_path . $mutex_filename, 'w');
 else
 $mutex = @sem_get($sem_id, 1, 0644 | IPC_CREAT, 1);
}

function wp_cache_writers_entry() {
 global $use_flock, $mutex, $cache_path, $mutex_filename;

 if( !$mutex )
 return false;

 if ($use_flock)
 flock($mutex,  LOCK_EX);
 else
 sem_acquire($mutex);

 return true;
}

function wp_cache_writers_exit() {
 global $use_flock, $mutex, $cache_path, $mutex_filename;

 if( !$mutex )
 return false;

 if ($use_flock)
 flock($mutex,  LOCK_UN);
 else
 sem_release($mutex);
}

function get_current_url_supercache_dir() {
 global $cached_direct_pages, $cache_path;
 $uri = preg_replace('/[ <>\'\"\r\n\t\(\)]/', '', str_replace( '/index.php', '/', str_replace( '..', '', preg_replace("/(\?.*)?$/", '', $_SERVER['REQUEST_URI'] ) ) ) );
 $dir = strtolower(preg_replace('/:.*$/', '',  $_SERVER["HTTP_HOST"])) . $uri; // To avoid XSS attacs
 $dir = trailingslashit( $cache_path . 'supercache/' . $dir );
 if( is_array( $cached_direct_pages ) &amp;&amp; in_array( $_SERVER[ 'REQUEST_URI' ], $cached_direct_pages ) ) {
 $dir = trailingslashit( ABSPATH . $uri );
 }
 $dir = str_replace( '//', '/', $dir );
 return $dir;
}

function wp_cache_ob_callback($buffer) {
 global $cache_path, $cache_filename, $meta_file, $wp_start_time, $supercachedir;
 global $new_cache, $wp_cache_meta_object, $file_expired, $blog_id, $cache_compression;
 global $wp_cache_gzip_encoding, $super_cache_enabled, $cached_direct_pages;
 global $wp_cache_404;

 $new_cache = true;

 /* Mode paranoic, check for closing tags
 * we avoid caching incomplete files */

 if( $wp_cache_404 ) {
 $new_cache = false;
 $buffer .= "\n<!-- Page not cached by WP Super Cache. 404. -->\n";
 }

 if (!preg_match('/(<\/html>|<\/rss>|<\/feed>)/i',$buffer) ) {
 $new_cache = false;
 $buffer .= "\n<!-- Page not cached by WP Super Cache. No closing HTML tag. Check your theme. -->\n";
 }

 if( !$new_cache )
 return $buffer;

 $duration = wp_cache_microtime_diff($wp_start_time, microtime());
 $duration = sprintf("%0.3f", $duration);
 $buffer .= "\n<!-- Dynamic Page Served (once) in $duration seconds -->\n";

 if( !wp_cache_writers_entry() ) {
 $buffer .= "\n<!-- Page not cached by WP Super Cache. Could not get mutex lock. -->\n";
 return $buffer;
 }

 $mtime = @filemtime($cache_path . $cache_filename);
 /* Return if:
 the file didn't exist before but it does exist now (another connection created)
 OR
 the file was expired and its mtime is less than 5 seconds
 */

 if( !((!$file_expired &amp;&amp; $mtime) || ($mtime &amp;&amp; $file_expired &amp;&amp; (time() - $mtime) < 5)) ) {
 $dir = get_current_url_supercache_dir();
 $supercachedir = $cache_path . 'supercache/' . preg_replace('/:.*$/', '',  $_SERVER["HTTP_HOST"]);
 if( !empty( $_GET ) || is_feed() || ( $super_cache_enabled == true &amp;&amp; is_dir( substr( $supercachedir, 0, -1 ) . '.disabled' ) ) )
 $super_cache_enabled = false;

 $fr = @fopen($cache_path . $cache_filename, 'w');
 if (!$fr) {
 $buffer .= "<!-- File not cached! Super Cache Couldn't write to: " . str_replace( ABSPATH, '', $cache_path ) . $cache_filename . " -->\n";
 return $buffer;
 }
 if( $super_cache_enabled ) {
 if( @is_dir( $dir ) == false )
 @wp_mkdir_p( $dir );

 $user_info = wp_cache_get_cookies_values();
 $do_cache = apply_filters( 'do_createsupercache', $user_info );
 if( $user_info == '' || $do_cache === true ) {
 $cache_fname = "{$dir}index.html";
 $tmp_cache_filename = tempnam( $dir, "wpsupercache");
 $fr2 = @fopen( $tmp_cache_filename, 'w' );
 if( $cache_compression )
 $gz = @fopen( $tmp_cache_filename . ".gz", 'w');
 }
 }

 if (preg_match('/<!--mclude|<!--mfunc/', $buffer)) { //Dynamic content
 $store = preg_replace('|<!--mclude (.*?)-->(.*?)<!--/mclude-->|is',
 "<!--mclude-->\n<?php include_once('" . ABSPATH . "$1'); ?>\n<!--/mclude-->", $buffer);
 $store = preg_replace('|<!--mfunc (.*?)-->(.*?)<!--/mfunc-->|is',
 "<!--mfunc-->\n<?php $1 ;?>\n<!--/mfunc-->", $store);
 $wp_cache_meta_object->dynamic = true;
 /* Clean function calls in tag */
 $buffer = preg_replace('|<!--mclude (.*?)-->|is', '<!--mclude-->', $buffer);
 $buffer = preg_replace('|<!--mfunc (.*?)-->|is', '<!--mfunc-->', $buffer);
 fputs($fr, $store);
 if( $fr2 )
 fputs($fr2, $store . '<!-- super cache -->' );
 if( $gz )
 fputs($gz, gzencode( $store . '<!-- super cache gz -->', 1, FORCE_GZIP ) );
 } else {
 $log = "<!-- Cached page served by WP-Super-Cache -->\n";

 if( $gz || $wp_cache_gzip_encoding ) {
 $gzdata = gzencode( $buffer . $log . "<!-- Compression = gzip -->", 1, FORCE_GZIP );
 $gzsize = strlen($gzdata);
 }
 if ($wp_cache_gzip_encoding) {
 array_push($wp_cache_meta_object->headers, 'Content-Encoding: ' . $wp_cache_gzip_encoding);
 array_push($wp_cache_meta_object->headers, 'Vary: Accept-Encoding, Cookie');
 array_push($wp_cache_meta_object->headers, 'Content-Length: ' . strlen($gzdata));
 // Return uncompressed data &amp; store compressed for later use
 fputs($fr, $gzdata);
 }else{ // no compression
 array_push($wp_cache_meta_object->headers, 'Vary: Cookie');
 fputs($fr, $buffer.$log);
 }
 if( $fr2 )
 fputs($fr2, $buffer . '<!-- super cache -->' );
 if( $gz )
 fwrite($gz, $gzdata );
 }
 $new_cache = true;
 fclose($fr);
 if( $fr2 ) {
 fclose($fr2);
 @chmod( $tmp_cache_filename, 0666 &amp; ~umask());
 if( !@rename( $tmp_cache_filename, $cache_fname ) ) {
 unlink( $cache_fname );
 rename( $tmp_cache_filename, $cache_fname );
 }
 }
 if( $gz ) {
 fclose($gz);
 if( !@rename( $tmp_cache_filename . '.gz', $cache_fname . '.gz' ) ) {
 unlink( $cache_fname . '.gz' );
 rename( $tmp_cache_filename . '.gz', $cache_fname . '.gz' );
 }
 }
 }
 wp_cache_writers_exit();
 return $buffer;
}

function wp_cache_phase2_clean_cache($file_prefix) {
 global $cache_path;

 if( !wp_cache_writers_entry() )
 return false;
 if ( ($handle = opendir( $cache_path )) ) {
 while ( false !== ($file = readdir($handle))) {
 if ( preg_match("/^$file_prefix/", $file) ) {
 @unlink($cache_path . $file);
 }
 }
 closedir($handle);
 }
 wp_cache_writers_exit();
}

function prune_super_cache($directory, $force = false, $rename = false) {
 global $cache_max_time, $cache_path, $super_cache_enabled, $cache_rebuild_files;

 if( !is_admin() &amp;&amp; $super_cache_enabled == 0 )
 return false;

 if( !isset( $cache_max_time ) )
 $cache_max_time = 3600;

 $now = time();

 $protected_directories = array( $cache_path . '.htaccess', $cache_path . 'meta', $cache_path . 'supercache' );

 $oktodelete = false;
 if (is_dir($directory)) {
 $directory = trailingslashit( $directory );
 $entries = glob($directory. '*');
 if( is_array( $entries ) &amp;&amp; !empty( $entries ) ) foreach ($entries as $entry) {
 if ($entry != '.' &amp;&amp; $entry != '..') {
 prune_super_cache( $entry, $force, $rename );
 if( is_dir( $entry ) &amp;&amp; ( $force || @filemtime( $entry ) + $cache_max_time <= $now ) ) {
 $oktodelete = true;
 if( in_array( $entry, $protected_directories ) )
 $oktodelete = false;
 if( $oktodelete &amp;&amp; !$rename )
 @rmdir( addslashes( $entry ) );
 }
 }
 }
 } elseif( is_file($directory) &amp;&amp; ($force || filemtime( $directory ) + $cache_max_time <= $now ) ) {
 $oktodelete = true;
 if( in_array( $directory, $protected_directories ) )
 $oktodelete = false;
 if( $oktodelete &amp;&amp; !$rename ) {
 @unlink( addslashes( $directory ) );
 } elseif( $oktodelete &amp;&amp; $rename ) {
 if( $cache_rebuild_files &amp;&amp; substr( $directory, -14 ) != '.needs-rebuild' ) {
 if( @rename($directory, $directory . '.needs-rebuild') )
 @touch( $directory . '.needs-rebuild' );
 } else {
 @unlink( $directory );
 }

 }
 }
}

function wp_cache_phase2_clean_expired($file_prefix) {
 global $cache_path, $cache_max_time;

 clearstatcache();
 if( !wp_cache_writers_entry() )
 return false;
 $now = time();
 if ( ($handle = opendir( $cache_path )) ) {
 while ( false !== ($file = readdir($handle))) {
 if ( preg_match("/^$file_prefix/", $file) &amp;&amp;
 (filemtime($cache_path . $file) + $cache_max_time) <= $now  ) {
 @unlink($cache_path . $file);
 @unlink($cache_path . 'meta/' . str_replace( '.html', '.meta', $file ) );
 continue;
 }
 if($file != '.' &amp;&amp; $file != '..') {
 if( is_dir( $cache_path . $file ) == false &amp;&amp; (filemtime($cache_path . $file) + $cache_max_time) <= $now  ) {
 if( substr( $file, -9 ) != '.htaccess' )
 @unlink($cache_path . $file);
 }
 }
 }
 closedir($handle);
 prune_super_cache( $cache_path . 'supercache' );
 }

 wp_cache_writers_exit();
}

function wp_cache_shutdown_callback() {
 global $cache_path, $cache_max_time, $file_expired, $file_prefix, $meta_file, $new_cache, $wp_cache_meta_object, $known_headers, $blog_id, $wp_cache_gc;

 $wp_cache_meta_object->uri = $_SERVER["SERVER_NAME"].preg_replace('/[ <>\'\"\r\n\t\(\)]/', '', $_SERVER['REQUEST_URI']); // To avoid XSS attacs
 $wp_cache_meta_object->blog_id=$blog_id;
 $wp_cache_meta_object->post = wp_cache_post_id();

 $response = wp_cache_get_response_headers();
 foreach ($known_headers as $key) {
 if(isset($response[$key])) {
 array_push($wp_cache_meta_object->headers, "$key: " . $response[$key]);
 }
 }
 /* Not used because it gives problems with some
 * PHP installations
 if (!$response{'Content-Length'}) {
 // WP does not set content size
 $content_size = ob_get_length();
 @header("Content-Length: $content_size");
 array_push($wp_cache_meta_object->headers, "Content-Length: $content_size");
 }
 */

 if (!isset( $response['Last-Modified'] )) {
 $value = gmdate('D, d M Y H:i:s') . ' GMT';
 /* Dont send this the first time */
 /* @header('Last-Modified: ' . $value); */
 array_push($wp_cache_meta_object->headers, "Last-Modified: $value");
 }
 if (!$response['Content-Type'] &amp;&amp; !$response['Content-type']) {
 // On some systems, headers set by PHP can't be fetched from
 // the output buffer. This is a last ditch effort to set the
 // correct Content-Type header for feeds, if we didn't see
 // it in the response headers already. -- dougal
 if (is_feed()) {
 $type = get_query_var('feed');
 $type = str_replace('/','',$type);
 switch ($type) {
 case 'atom':
 $value = "application/atom+xml";
 break;
 case 'rdf':
 $value = "application/rdf+xml";
 break;
 case 'rss':
 case 'rss2':
 default:
 $value = "application/rss+xml";
 }
 } else { // not a feed
 $value = 'text/html';
 }
 $value .=  "; charset=\"" . get_option('blog_charset')  . "\"";

 @header("Content-Type: $value");
 array_push($wp_cache_meta_object->headers, "Content-Type: $value");
 }

 @ob_end_flush();
 flush(); //Ensure we send data to the client
 if ($new_cache) {
 $serial = serialize($wp_cache_meta_object);
 if( !wp_cache_writers_entry() )
 return false;
 $fr = @fopen($cache_path . 'meta/' . $meta_file, 'w');
 if( !$fr )
 @mkdir( $cache_path . 'meta' );
 $fr = fopen($cache_path . 'meta/' . $meta_file, 'w');
 fputs($fr, $serial);
 fclose($fr);
 wp_cache_writers_exit();
 }

 if( !isset( $wp_cache_gc ) )
 $wp_cache_gc = 3600;
 $last_gc = get_option( "wpsupercache_gc_time" );

 if( !$last_gc ) {
 update_option( 'wpsupercache_gc_time', time() );
 return;
 }

 if( $last_gc > ( time() - $wp_cache_gc ) ) // do garbage collection once every X hours.
 return;
 update_option( 'wpsupercache_gc_time', time() );

 // we delete expired files, using a wordpress cron event
 // since flush() does not guarantee hand-off to client - problem on Win32 and suPHP
 if(!wp_next_scheduled('wp_cache_gc')) wp_schedule_single_event(time() + 10 , 'wp_cache_gc');
}

function wp_cache_no_postid($id) {
 return wp_cache_post_change(wp_cache_post_id());
}

function wp_cache_get_postid_from_comment($comment_id) {
 global $super_cache_enabled;
 $comment = get_comment($comment_id, ARRAY_A);
 $postid = $comment['comment_post_ID'];
 // Do nothing if comment is not moderated
 // http://ocaoimh.ie/2006/12/05/caching-wordpress-with-wp-cache-in-a-spam-filled-world
 if( !preg_match('/wp-admin\//', $_SERVER['REQUEST_URI']) )
 if( $comment['comment_approved'] == 'spam' ) { // changed from 1 to "spam"
 return $post_id;
 } elseif( $comment['comment_approved'] == '0' ) {
 $super_cache_enabled = 0; // don't remove the super cache static file until comment is approved
 }
 // We must check it up again due to WP bugs calling two different actions
 // for delete, for example both wp_set_comment_status and delete_comment
 // are called when deleting a comment
 if ($postid > 0)
 return wp_cache_post_change($postid);
 else
 return wp_cache_post_change(wp_cache_post_id());
}

function wp_cache_post_edit($post_id) {
 global $wp_cache_clear_on_post_edit, $cache_path;
 if( $wp_cache_clear_on_post_edit ) {
 prune_super_cache( $cache_path, true );
 } else {
 wp_cache_post_change( $post_id );
 }
}

function wp_cache_post_change($post_id) {
 global $file_prefix, $cache_path, $blog_id, $blogcacheid, $super_cache_enabled;
 static $last_processed = -1;

 if ($post_id == $last_processed) return $post_id;
 $last_processed = $post_id;
 if( !wp_cache_writers_entry() )
 return $post_id;

 $permalink = trailingslashit( str_replace( get_option( 'siteurl' ), '', post_permalink( $post_id ) ) );
 if( $super_cache_enabled ) {
 $siteurl = trailingslashit( strtolower( preg_replace( '/:.*$/', '', str_replace( 'http://', '', get_option( 'home' ) ) ) ) );
 // make sure the front page has a rebuild file
 prune_super_cache( $cache_path . 'supercache/' . $siteurl . 'index.html', true, true );
 prune_super_cache( $cache_path . 'supercache/' . $siteurl . 'index.html.gz', true, true );
 if( $post_id != 0 ) {
 $permalink = trailingslashit( str_replace( get_option( 'home' ), '', post_permalink( $post_id ) ) );
 $dir = $cache_path . 'supercache/' . $siteurl;
 prune_super_cache( $dir . $permalink, true, true );
 @rmdir( $dir . $permalink );
 prune_super_cache( $dir . 'page/', true );
 }
 }

 $meta = new CacheMeta;
 $matches = array();
 if ( ($handle = opendir( $cache_path . 'meta/' )) ) {
 while ( false !== ($file = readdir($handle))) {
 if ( preg_match("/^({$file_prefix}{$blogcacheid}.*)\.meta/", $file, $matches) ) {
 $meta_pathname = $cache_path . 'meta/' . $file;
 $content_pathname = $cache_path . $matches[1] . ".html";
 $meta = unserialize(@file_get_contents($meta_pathname));
 if ($post_id > 0 &amp;&amp; $meta) {
 if ($meta->blog_id == $blog_id  &amp;&amp; (!$meta->post || $meta->post == $post_id) ) {
 @unlink($meta_pathname);
 @unlink($content_pathname);
 }
 } elseif ($meta->blog_id == $blog_id) {
 @unlink($meta_pathname);
 @unlink($content_pathname);
 }

 }
 }
 closedir($handle);
 }
 wp_cache_writers_exit();
 return $post_id;
}

function wp_cache_microtime_diff($a, $b) {
 list($a_dec, $a_sec) = explode(' ', $a);
 list($b_dec, $b_sec) = explode(' ', $b);
 return $b_sec - $a_sec + $b_dec - $a_dec;
}

function wp_cache_post_id() {
 global $posts, $comment_post_ID, $post_ID;
 // We try hard all options. More frequent first.
 if ($post_ID > 0 ) return $post_ID;
 if ($comment_post_ID > 0 )  return $comment_post_ID;
 if (is_single() || is_page()) return $posts[0]->ID;
 if (isset( $_GET[ 'p' ] ) &amp;&amp; $_GET['p'] > 0) return $_GET['p'];
 if (isset( $_POST[ 'p' ] ) &amp;&amp; $_POST['p'] > 0) return $_POST['p'];
 return 0;
}

function wp_cache_gc_cron() {
 global $file_prefix;
 wp_cache_phase2_clean_expired($file_prefix);
}

?>

&amp;nbsp;