• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 490
  • Last Modified:

different versions of php, windows has a change in the same code

On a new server
this code is going to

line 3
intiateAC();
which is prompting user for login information

this happens I think 1 out of 25 times

this never happened on the old php 5.2 windows web server 2008

but happens on the new php 5.3.6 windows server 2008 r2 standard

<?php
require_once('inc/common.php');
intiateAC();

if(isset($_GET['a'])) {
  $action = sanitize_str($_GET['a']);
} else {
  $action = "";
}

if(isset($_POST['a'])) {
  $a = sanitize_str($_POST['a']);
}

if(isset($_GET['txt'])) {
  $text = sanitize_str($_GET['txt']);  
}
if(isset($_GET['orderid'])) {
  $orderid = sanitize_int($_GET['orderid']);
}

if(!empty($a)) {
  if(isset($_POST['orderid'])) {
    $orderid = sanitize_int($_POST['orderid']);
  }

  switch ($a) {
}

Open in new window

0
rgb192
Asked:
rgb192
  • 3
  • 2
  • 2
1 Solution
 
Lukasz ChmielewskiCommented:
can you post the code of initiateAC() ?
0
 
pixalaxCommented:
+ Roads_Roads. We can't see what is initiateAC() function is doing.

PHP 5.3.x has many differences comparing to versions under PHP 5.3. Joomla, WP, etc, such systems are not working properly with PHP 5.3, that's why it is quite hard to find hosting for PHP 5.3 & above.
0
 
pixalaxCommented:
Forgot to mention,
I had a problem with SESSIONS with a system which was running on PHP 5.2.13 (I guess it was .13, anyway it is not important) when I tried to run it with PHP 5.3.x. I had to sit and change whole structure of SESSIONS so visitors and also admins could log in.

Since your problem is also related to log-ins, I would suggest you to check your SESSIONS.
0
 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

 
Lukasz ChmielewskiCommented:
@pixalax
I see we cannot see that. Or we can't as we're not allowed ? That's why I asked the author to post the function body.
0
 
pixalaxCommented:
Sorry, Roads_Roads if I couldn't explain myself good. I meant +1 (I agree with you).
0
 
rgb192Author Commented:
function intiate AC() is a part of common.php


function intiateAC() {
      global $db;

      if(!isset($_SESSION['loggedin'])) {
            $url = OW_URL . 'login.php';
            header('Location: '.$url);
            die();//Kills the PHP process, otherwise the page would continue to be executed despite a url redirection
      }
}


and I attach the entire common.php file that is included
<?php
/* --------------------------------------------------------------

    Required PHP Extensions
        PDO w/ ODBC
        MICROSOFT NATIVE SQL CLIENT
        MCRYPT
        CURL (Ensure that libeay32.dll and ssleay32.dll  ARE IN THE PHP PATH)
-------------------------------------------------------------- */


ini_set('max_execution_time', 30*20);
ini_set('memory_limit', -1);
ini_set('session.name', 'OW');


error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);

define('SALT_LENGTH', 9);

$data = array_reverse(explode('.', $_SERVER['HTTP_HOST']));

$url='http://'.$data[2].'.'.$data[1].'.com/';
define ('OW_URL',"$url");
define('TAXRATE', '0.08375');
define('REFUND_PASSWORD', 'pass');

//Set timezone to New York
date_default_timezone_set('America/New_York');

function recordPHPerror($error_number, $error_string, $error_file, $error_line, $error_context) {
      $mail_body = "
        <pre>
        URL: ".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."
        Error Number: $error_number
        Error Message: $error_string
        Error Time: ".$_SERVER['REQUEST_TIME']."
        File: $error_file
        Line: $error_line
        Error Backtrace:

        ".var_export(debug_backtrace(), true)."

        Error Context:

        ".var_export($error_context, true)."</pre>";
    
file_put_contents("error.txt","$mail_body",FILE_APPEND);  

    return false;
}

/*--------------------------------------------------------------
    Required Files
-------------------------------------------------------------- */

require_once('functions/creditcard.php');
require_once('functions/db.php');
require_once('functions/display.php');

require_once('functions/editorder.php');
require_once('functions/email.php');
require_once('functions/history.php');
require_once('functions/order.php');
require_once('functions/package.php');

require_once('functions/payments.php');
require_once('functions/permission.php');
require_once('functions/print.php');
require_once('functions/product.php');

require_once('functions/inventory5.php');
require_once('functions/users.php');
require_once('functions/htmlMimeMail5/htmlMimeMail5.php');



/*--------------------------------------------------------------
    Application Constants
-------------------------------------------------------------- */
define("PAYMENTTYPESUK", "Paypal,Paypal Terminal,HDEW Credit Card,Bank Transfer,Google Checkout,AmazonUK");
define("PAYMENTTYPES", "Paypal,Visa,Mastercard,AMEX,Discover,Wire,Cash,Check,Google,Amazon,Maestro");

/*--------------------------------------------------------------
    DB Objects
-------------------------------------------------------------- */
$user = "user";
$pass = "pass";

$ip = "ipaddress";
$database = "database";
$dbname = "dbname";

$db = new PDO("odbc:Driver={SQL Native Client};Server=$ip;Database=$database;dbname=$dbname",$user,$pass);
$db2 = new PDO("odbc:Driver={SQL Native Client};Server=$ip;Database=$database;dbname=$dbname",$user,$pass);


/*--------------------------------------------------------------------------------
    PHP Utility Functions for $db object
    Database:
        dbfetcharray -         returns array from a query
        dbfetchsingle -     returns single row from a query
        dbfetch -             returns single value
        dbquery -             returns result of PDOObject->query
        dbwrite -             returns result of PDOObject->query using a second db object
        dbinsertandgetid - runs a insert query then returns the id of the item inserted - Does not work with MSSQL

-------------------------------------------------------------------------------- */

function dbfetcharray($sql) {
    global $db;
    try {
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $rs = $db->prepare($sql);
        $rs->execute();
    recordSQLError("a1",$sql,"");
        return $rs->fetchAll();
    }
    catch(PDOException $e) {
        recordSQLError("dbfetcharray",$sql,$e->getMessage());
    }
}



function dbfetchsingle($sql) {
    global $db;
    try {
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $rs = $db->prepare($sql);
        $rs->execute();
        $rs = $rs->fetchAll();
        $rs = $rs[0];
    recordSQLError("s1",$sql,"");
        return $rs;
    }
    catch(PDOException $e) {
        recordSQLError("dbfetchsingle",$sql,$e->getMessage());
    }
}

function dbquery($sql) {
    global $db;
    try {
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    recordSQLError("q1",$sql,"");
        return $db->query($sql);
    }
    catch(PDOException $e) {
        recordSQLError("dbquery",$sql,$e->getMessage());
    }
}


function dbwrite($sql) {
    global $db2;
    try {
        $db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db2->query($sql);
    }
    catch(PDOException $e) {
        recordSQLError("dbwrite",$sql,$e->getMessage());
    }
}

function dbfetch($sql) {
    global $db;
    try {
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $f = $db->prepare($sql);
        $f->execute();
        recordSQLError("f1",$sql,"");
        return $f->fetchColumn();
    }
    catch(PDOException $e) {
        recordSQLError("dbfetch",$sql,$e->getMessage());
    }
}


//Does not work with MSSQL or ODBC driver
function dbinsertandgetid($sql) {
    /*
    global $db;
    try {
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $rs = $db->prepare($sql);
        $rs->execute();
        return $db->lastInsertId();
    }
    catch(PDOException $e) {
        recordSQLError("dbfetch",$sql,$e->getMessage());
    }*/
    recordSQLError("dbinsertandgetid",$sql,"Depricated Function");
}

function recordSQLError($function,$sql,$error) {
$logfile="dberrorlog.txt";
    $fp = fopen($logfile, 'a');
  fwrite($fp, $error);
    fwrite($fp, date("m/d h:i:sA"));
    fwrite($fp, " | $function | ");
    //fwrite($fp, " | SQL: ");
    fwrite($fp, $sql);
    //fwrite($fp, " | Error: ");
  //fwrite($fp, " ||| ");
    fwrite($fp, "\r\n");
    fclose($fp);
}

function recordOLDSQLError($function,$sql,$error) {
$logfile="dberrorlog.txt";
    $fp = fopen($logfile, 'a');
    fwrite($fp, date("m/d/Y h:i:sA"));
    fwrite($fp, " | $function | ");
    fwrite($fp, " | SQL: ");
    fwrite($fp, $sql);
    fwrite($fp, " | Error: ");
    fwrite($fp, $error);
    fwrite($fp, "\r\n");
    fclose($fp);
}

function datetime($syntax,$datetime) {
    $year = substr($datetime,0,4);
    $month = substr($datetime,5,2);
    $day = substr($datetime,8,2);
    $hour = substr($datetime,11,2);
    $min = substr($datetime,14,2);
    $sec = substr($datetime,17,2);

    return date($syntax,mktime($hour,$min,$sec,$month,$day,$year));
}

function generateHash($plainText, $salt = null) {
    if ($salt === null) {
        $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
    }
    else {
        $salt = substr($salt, 0, SALT_LENGTH);
    }
    return $salt . sha1($salt . $plainText);
}

function sanitize_str($string) {
    return filter_var($string, FILTER_SANITIZE_STRING);
}

function sanitize_int($string) {
    return filter_var($string, FILTER_SANITIZE_NUMBER_INT);
}

function sanitize_float($string) {
    return filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
}

function sanitize_db($string) {
    return "'" . str_replace("'", "''", $string) . "'";
}

function sanitize_db2($string) {
    return str_replace("'", "''", $string);
}

/*--------------------------------------------------------------
    PHP Encryption Functions
-------------------------------------------------------------- */
//The key must be 32 characters long in order to take advantage of the 128bits in AES128
$key = md5('secret');

function encrypt($text) {
    global $key;

    srand((double) microtime() * 1000000); //for sake of MCRYPT_RAND

    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_ECB, $iv);
    $encode = base64_encode($encrypted);

    return $encode;
}

function decrypt($encoded) {
    global $key;
    $decoded = base64_decode($encoded);
    srand((double) microtime() * 1000000); //for sake of MCRYPT_RAND
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $decoded, MCRYPT_MODE_ECB, $iv);

    return trim($decrypted);
}

/*--------------------------------------------------------------
    Custom PHP PDO Session Handler
-------------------------------------------------------------- */
$sh = new session($db);
class session {
    private $_session;
    public $maxTime;
    private $db;

    public function __construct(PDO $database) {
        $this->db = $database;
        $this->maxTime['access'] = time();
        $this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');

        session_set_save_handler(array($this, '_open'), array($this, '_close'),    array($this, '_read'), array($this, '_write'), array($this, '_destroy'), array($this, '_clean'));
        register_shutdown_function('session_write_close');
        session_start();
        $this->_secure();
    }

    public function _open() {
        return true;
    }

    public function _close() {
        $this->_clean($this->maxTime['gc']);
        return true;
    }

    public function _read($id) {
        $getData = $this->db->prepare("SELECT data FROM sessions WHERE id = ?");
        $getData->bindParam(1, $id);
        $getData->execute();

        $allData = $getData->fetch(PDO::FETCH_ASSOC);
        $totalData = count($allData);
        $hasData = (bool) $totalData >= 1;
        $this->_clean($this->maxTime['gc']);

        return $hasData ? $allData['data'] : '';
    }

    public function _write($id, $data) {
        $getData = $this->db->prepare("DELETE FROM sessions WHERE id = ?");
        $getData->bindParam(1, $id);
        $getData->execute();
        $getData = $this->db->prepare("INSERT INTO sessions VALUES (?, ?, ?)");
        $getData->bindParam(1, $id);
        $getData->bindParam(2, $this->maxTime['access']);
        $getData->bindParam(3, $data);
        return $getData->execute();
    }

    public function _destroy($id) {
        $sql = "DELETE FROM sessions WHERE id = '$id'";
        dbquery($sql);
    }

    public function _clean($max) {
        $old = time();
        $old -= 3600;
        //$old = ($this->maxTime['access'] - $max);

        $getData = $this->db->prepare("DELETE FROM sessions WHERE access < ?");
        $getData->bindParam(1, $old);
        return $getData->execute();
    }
    public function _secure() {
        //Disabled due to conflicts when running many ajax requests. Race problem occurs, http://www.chipmunkninja.com/g@

        //Recreate SessionID and delete old sessions
        //$old_session_id = session_id();
        //session_regenerate_id();
        //$this->_destroy($old_session_id);
    }
}

/*--------------------------------------------------------------
    Session Related Functions
-------------------------------------------------------------- */
//This function handles authorization of all requested pages
function intiateAC() {
    global $db;

    if(!isset($_SESSION['loggedin'])) {
        $url = OW_URL . 'login.php';
        header('Location: '.$url);
        die();//Kills the PHP process, otherwise the page would continue to be executed despite a url redirection
    }
}

function checkPermission($permission) {
    //Permissions are seperated by a , and a space keep in mind if there are check permission errors!!!!!
    if(in_array($permission,$_SESSION['permissions'])) {
        return true;
    }
    else {
        return false;
    }
}

function fetchUsername($userid) {
    global $db;
    $sql = "SELECT name FROM users WHERE userid = '$userid'";
    return dbfetch2($sql);
}

function recordHistory($orderid,$level,$event) {
  

    $theirip=$_SERVER['REMOTE_ADDR'];
    $ip = getenv("REMOTE_ADDR"); 
  $sql = "INSERT INTO orderhistory (orderid, date, userid, levelid, event,theirip,ip) VALUES ('$orderid', getdate(),'$_SESSION[userid]','$level','$event','$theirip','$ip')";
  dbquery2($sql);
  
}

function om_die($message) {
    // Display template and message in a pretty layout
}

function om_dielogin($message) {
    // Display template and message in a pretty layout with login screen
}

/*--------------------------------------------------------------
    Number Formatting Functions
-------------------------------------------------------------- */
//Not a replacement of PHPs money_format

function money_round_usd($amount) {
    return number_format($amount, 2, '.',',');
}

function format_ccnumber($number) {
    if(is_numeric($number)) {
        if(strlen($number) == 16) {
            return substr($number,0,4) . '-' . substr($number,4,4) . '-' . substr($number,8,4) . '-' . substr($number,12,4);
        }
        else {
            return substr($number,0,4) . '-' . substr($number,4,4) . '-' . substr($number,8,4) . '-' . substr($number,12,4);
            //return substr($number,0,4) . '-' . substr($number,4,7) . '-' . substr($number,11,5);
            //return $number;
        }
    } else {
        return $number;
    }
}


function format_money($amount,$currency) {
    if($amount>0.00) {
        $returnamount = '<span class="green">';
    }
    else {
        $returnamount = '<span class="red">';
    }
    switch ($currency) {
        case 'USD':
            setlocale(LC_MONETARY, 'en_US');
            $returnamount .= money_format('%i', $amount) . "";
            break;
        case 'GBP':
            setlocale(LC_MONETARY, 'en_GB');
            $returnamount .= money_format('%i', $amount) . "";
            break;
    }
    return $returnamount . '</span>';
}

//Actual replacement of PHP money_format since this application is on a windows machine
if (!function_exists('money_format')) {
    function money_format($format, $number)
    {
        $regex  = array(
           '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?(?:#([0-9]+))?',
           '(?:\.([0-9]+))?([in%])/'
        );
        $regex = implode('', $regex);
        if (setlocale(LC_MONETARY, null) == '') {
            setlocale(LC_MONETARY, '');
        }
        $locale = localeconv();
        $number = floatval($number);
        if (!preg_match($regex, $format, $fmatch)) {
            trigger_error("No format specified or invalid format",
E_USER_WARNING);
            return $number;
        }
        $flags = array(
            'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ?
$match[1] : ' ',
            'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
            'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
$match[0] : '+',
            'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
            'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
        );
        $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
        $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
        $right      = trim($fmatch[4]) ? (int)$fmatch[4] :
$locale['int_frac_digits'];
        $conversion = $fmatch[5];
        $positive = true;
        if ($number < 0) {
            $positive = false;
            $number  *= -1;
        }
        $letter = $positive ? 'p' : 'n';
        $prefix = $suffix = $cprefix = $csuffix = $signal = '';
        if (!$positive) {
            $signal = $locale['negative_sign'];
            switch (true) {
                case $locale['n_sign_posn'] == 0 || $flags['signal'] ==
'(':
                    $prefix = '(';
                    $suffix = ')';
                    break;
                case $locale['n_sign_posn'] == 1:
                    $prefix = $signal;
                    break;
                case $locale['n_sign_posn'] == 2:
                    $suffix = $signal;
                    break;
                case $locale['n_sign_posn'] == 3:
                    $cprefix = $signal;
                    break;
                case $locale['n_sign_posn'] == 4:
                    $csuffix = $signal;
                    break;
            }
        }
        if (!$flags['nosimbol']) {
            $currency  = $cprefix;
            $currency .= (
                $conversion == 'i' ?
                $locale['int_curr_symbol'] :
                $locale['currency_symbol']
            );
            $currency .= $csuffix;
        } else {
            $currency = '';
        }
        $space    = $locale["{$letter}_sep_by_space"] ? ' ' : '';

        $number = number_format($number, $right,
$locale['mon_decimal_point'],
                      $flags['nogroup'] ? '' :
$locale['mon_thousands_sep']
                  );
        $number = explode($locale['mon_decimal_point'], $number);

        $n = strlen($prefix) + strlen($currency);
        if ($left > 0 && $left > $n) {
            if ($flags['isleft']) {
                $number[0] .= str_repeat($flags['fillchar'], $left - $n);
            } else {
                $number[0] = str_repeat($flags['fillchar'], $left - $n) .
$number[0];
            }
        }
        $number = implode($locale['mon_decimal_point'], $number);
        if ($locale["{$letter}_cs_precedes"]) {
            $number = $prefix . $currency . $space . $number . $suffix;
        } else {
            $number = $prefix . $number . $space . $currency . $suffix;
        }
        if ($width > 0) {
            $number = str_pad($number, $width, $flags['fillchar'],
$flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
        }
        $format = str_replace($fmatch[0], $number, $format);
        return $format;
    }
}

Open in new window

0
 
rgb192Author Commented:
Thanks
0

Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now