Jump to content

Recommended Posts

Hi all

I have an issue with some php files that keep throwing an internal server error and I'm not sure what is causing it..

Posted below are the files.

dbc:

<?php
(c) Balakrishnan 2010. All Rights Reserved
Usage: This script can be used FREE of charge for any commercial or personal projects. Enjoy!

Limitations:
- This script cannot be sold.
- This script should have copyright notice intact. Dont remove it please...
- This script may not be provided for download except from its original site.

For further usage, please contact me.

Please complete wherever marked xxxxxxxxx

Note: If you use cpanel, the name will be like account_database
*************************************************************/

define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", "dataUser"); // set database user
define ("DB_PASS","password"); // set database password
define ("DB_NAME","myDB"); // set database name


$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");

/* Registration Type (Automatic or Manual)
1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$user_registration = 0;  // set 0 or 1

define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password

//define ("ADMIN_NAME", "admin"); // sp

/* Specify user levels */
define ("ADMIN_LEVEL", 6);
define ("USER_LEVEL", 0);
define ("GUEST_LEVEL", -1);



/*************** reCAPTCHA KEYS****************/
$publickey = "[removed]";
$privatekey = "[removed]";


/**** PAGE PROTECT CODE  ********************************
This code protects pages to only logged in users. If users have not logged in then it will redirect to login page.
If you want to add a new page and want to login protect, COPY this from this to END marker.
Remember this code must be placed on very top of any html or php page.
********************************************************/

function page_protect() {
session_start();

global $db;

/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
    if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
    {
        logout();
        exit;
    }
}

// before we allow sessions, we need to check authentication key - ckey and ctime stored in database

/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_name']) )
{
   if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])){
   /* we double check cookie expiry time against stored in database */
   
   $cookie_user_id  = filter($_COOKIE['user_id']);
   $rs_ctime = mysql_query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die(mysql_error());
   list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
   // coookie expiry
   if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {

      logout();
      }
/* Security check with untrusted cookies - dont trust value stored in cookie.       
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/

    if( !empty($ckey) && is_numeric($_COOKIE['user_id']) && isUserID($_COOKIE['user_name']) && $_COOKIE['user_key'] == sha1($ckey)  ) {
         session_regenerate_id(); //against session fixation attacks.
   
        $_SESSION['user_id'] = $_COOKIE['user_id'];
        $_SESSION['user_name'] = $_COOKIE['user_name'];
      /* query user level from database instead of storing in cookies */   
        list($user_level) = mysql_fetch_row(mysql_query("select user_level from users where id='$_SESSION[user_id]'"));

        $_SESSION['user_level'] = $user_level;
        $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
        
      } else {
      logout();
      }

  } else {
   header("Location: login.php");
   exit();
   }
}
}



function filter($data) {
   $data = trim(htmlentities(strip_tags($data)));
   
   if (get_magic_quotes_gpc())
      $data = stripslashes($data);
   
   $data = mysql_real_escape_string($data);
   
   return $data;
}



function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}

function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}

function ChopStr($str, $len)
{
    if (strlen($str) < $len)
        return $str;

    $str = substr($str,0,$len);
    if ($spc_pos = strrpos($str," "))
            $str = substr($str,0,$spc_pos);

    return $str . "...";
}   

function isEmail($email){
  return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}

function isUserID($username)
{
   if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
      return true;
   } else {
      return false;
   }
}   

function isURL($url)
{
   if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
      return true;
   } else {
      return false;
   }
}


function checkPwd($x,$y)
{
    //Checks if strings are empty

    if(empty($x) || empty($y) )
    {
        //Strings were empty
        return false;
    }
    else if(strlen($x) < 4 || strlen($y) < 4)
    {
        //String length too short
        return false;
    }
    else if(strcmp($x,$y) != 0)
    {
        //Strings do not match
        return false;
    }
    else
    {
        //Password Determined valid
        return true;

    }
}

function GenPwd($length = 7)
{
  $password = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels

  $i = 0;
   
  while ($i < $length) {

   
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
       
   
    if (!strstr($password, $char)) {
      $password .= $char;
      $i++;
    }

  }

  return $password;

}

function GenKey($length = 7)
{
  $password = "";
  $possible = "0123456789abcdefghijkmnopqrstuvwxyz";

  $i = 0;
   
  while ($i < $length) {

   
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
       
   
    if (!strstr($password, $char)) {
      $password .= $char;
      $i++;
    }

  }

  return $password;

}


function logout()
{
global $db;
session_start();

if(isset($_SESSION['user_id']) || isset($_COOKIE['user_id'])) {
mysql_query("update `users`
         set `ckey`= '', `ctime`= ''
         where `id`='$_SESSION[user_id]' OR  `id` = '$_COOKIE[user_id]'") or die(mysql_error());
}         

/************ Delete the sessions****************/
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_level']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy();//This last function completely destroys sessions.. the above is all redundant.

/* Delete the cookies*******************/
setcookie("user_id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");

header("Location: login.php");
}

// Password and salt generation

function PwdHash($pwd)
{
    $hashedPwd = md5($pwd);
   
    return $hashedPwd;
}

function checkAdmin() {

if($_SESSION['user_level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}

}

?>

 

faction:

<?php
/********************** FACTION.PHP**************************
This File handles Faction Chat
************************************************************/
include 'dbc.php';
page_protect();

//Msg Output String
$Output = '';

//%^^ Function to handle Member Gathering ^^%//
function getMembers($UserInfo, $ChatID = '0')
{   
   //Switch the Member Query based on group
   switch($ChatID)
   {
      case '2':
         //Leaders
         $MembrSQL = "SELECT user_name, Faction, FactionInv, RankName, id FROM users WHERE Rank >='6' AND Faction!='9999' ORDER BY user_name ASC";
         $ChatName = 'Leaders';
      break;
      
      case '1':
         //Faction
         $MembrSQL = "SELECT user_name, Faction, FactionInv, RankName, id FROM users WHERE Faction='".$UserInfo['Faction']."' ORDER BY user_name ASC";
         $ChatName = 'Faction';
      break;
      
      default:
         //Public
         $MembrSQL = "SELECT user_name, Faction, FactionInv, RankName, id FROM users ORDER BY user_name ASC";
         $ChatName = 'Public';
   }
   
   //@@^^ GET MEMBERS FROM DB ^^@@//
   $MemberQuery = mysql_query($MembrSQL) or die(mysql_error());
   $MEMBERS = '';//HOLDS MEMBER LIST AS STRING
   while($MembRow = mysql_fetch_array($MemberQuery))
   {
      //If Member is in a faction
      //Get the Faction Information
      if($MembRow['Faction'] != '9999')
      {
         $MembFactionQuery = mysql_query("SELECT Name, FullName FROM factions WHERE id='".$MembRow['Faction']."'") or die(mysql_error());
         $FactionInfo = mysql_fetch_assoc($MembFactionQuery);
         //$FactionInfo['Name'];
         //$FactionInfo['FullName'];   
      }
      
      //Check if current user is a leader
      //Double Check that user is in a faction
      if($UserInfo['Rank'] >= 6 && $UserInfo['Faction'] != '9999')
      {
         //@^^ User is Leader and in a Faction
         
         //Check if member is in same faction as user
         if($UserInfo['Faction'] == $MembRow['Faction'])
         {
            //@^^ Member is in Current users faction
                  
            //MemberName String w/Remove User
            $MEMBERS .= "<a style='color:red;' href='#' alt='Remove ".$MembRow['user_name']." from faction' title='Remove ".$MembRow['user_name']." from faction' onclick=\"confirmRemove('".$MembRow['user_name']."', '".$MembRow['id']."-".$MembRow['Faction']."', '$ChatName');\">[x]</a> ".$MembRow['user_name']." <span style='cursor:help;font-weight:bold;'>(".$MembRow['RankName'].")</span><br>".PHP_EOL;
         }
         else if($MembRow['Faction'] != '9999')
         {
            //@^^ Member is in different faction than user
            
            //Switch Member String based on ChatID
            switch($ChatID)
            {
               case '2':
                  //Leader Chat
                  
                  //MemberName String w/Faction Name
                  $MEMBERS .= $MembRow['user_name']." <span style='cursor:help;font-weight:bold;' alt='".htmlentities($FactionInfo['FullName'], ENT_QUOTES)."' title='".htmlentities($FactionInfo['FullName'], ENT_QUOTES)."'>[".$FactionInfo['Name']."]</span><br>".PHP_EOL;
               break;
               
               default:
                  //Public Chat
                  
                  //MemberName String Basic
                  $MEMBERS .= $MembRow['user_name']."<br>".PHP_EOL;
            }
         }
         else
         {
            //@^^ Member is not in a faction
            
            //Make sure that this member doesn't already have
            // an invite from the current users faction.
            $InvQue = explode('-', $MembRow['FactionInv']);
            
            if(in_array($UserInfo['Faction'], $InvQue))
            {   
               //Member Has Inv Already
               //MemberName String w/Pending Inv
               $MEMBERS .= $MembRow['user_name']." <span style='cursor:help;color:green;' alt='Faction Invite Pending...' title='Faction Invite Pending...'>(?)</span><br>".PHP_EOL;
            }
            else
            {
               //No pending Faction Inv for this member
               //MemberName String w/Invite User
               $MEMBERS .= $MembRow['user_name']." <a href='faction.php?ChatID=$ChatName&Inv=".$MembRow['id']."-".$UserInfo['Faction']."' alt='Invite ".$MembRow['user_name']." to faction' title='Invite ".$MembRow['user_name']." to faction'>[+]</a><br>".PHP_EOL;
            }
         }
      }
      else
      {
         //@^^ Non-Leader User
         
         //Check if the User is in a faction
         if($UserInfo['Faction'] != '9999')
         {
            //@^^ User in faction
            
            if($MembRow['user_name'] == $UserInfo['user_name'])
            {
               //@^^ User is the member!
               
               //Check for faction RankName
               if(!(empty($MembRow['RankName'])) && strtolower($MembRow['RankName']) != 'none')
               {
                  //@^^ Member Has RankName
                  
                  //MemberName String w/Remove User
                  $MEMBERS .= "<a style='color:red;' href='#' alt='Remove ".$MembRow['user_name']." from faction' title='Remove ".$MembRow['user_name']." from faction' onclick=\"confirmRemove('".$MembRow['user_name']."', '".$MembRow['id']."-".$MembRow['Faction']."', '$ChatName');\">[x]</a><span style='cursor:help;font-weight:bold;'> (".$MembRow['RankName'].") </span> ".$MembRow['user_name']."<br>".PHP_EOL;
               }
               else
               {
                  //@^^ Member Has No RankName
                  $MEMBERS .= "<a style='color:red;' href='#' alt='Remove ".$MembRow['user_name']." from faction' title='Remove ".$MembRow['user_name']." from faction' onclick=\"confirmRemove('".$MembRow['user_name']."', '".$MembRow['id']."-".$MembRow['Faction']."', '$ChatName');\">[x]</a> ".$MembRow['user_name']."<br>".PHP_EOL;
               }
            }
            else if($MembRow['Faction'] == $UserInfo['Faction'])
            {
               //@^^ Member In Users same Faction
               
               //Check for faction RankName
               if(!(empty($MembRow['RankName'])) && strtolower($MembRow['RankName']) != 'none')
               {
                  //@^^ Member Has RankName
                  
                  //MemberName String   w/Faction RankName
                  $MEMBERS .= $MembRow['user_name']." <span style='font-weight:bold;cursor:help; ' alt='".$FactionInfo['Name']."' title='".$FactionInfo['Name']."'>(".$MembRow['RankName'].")</span><br>".PHP_EOL;
               }
               else
               {
                  //@^^ Member doesn't have a rankname
                  
                  //MemberName String Basic
                  $MEMBERS .= $MembRow['user_name']."<br>".PHP_EOL;
               }
            }
            else
            {
               //@^^ User is in different Faction
               
               //MemberName String Basic
               $MEMBERS .= $MembRow['user_name']."<br>".PHP_EOL;
            }
         }
         else
         {
            //@^^ User not in faction
            
            //MemberName String Basic
            $MEMBERS .= $MembRow['user_name']."<br>".PHP_EOL;
         }
      }
   }
   return $MEMBERS;
}//END Get Members

//Check for a user
if(isset($_SESSION['user_id']))
{
   //User Found
   //^^ Get the current Username
   $CurrentUser = $_SESSION['user_id'];
   
   //^^ Get User info from DB
   $FindUser = mysql_query("SELECT user_name,Faction,FactionInv,Rank,RankName,id FROM users WHERE id='$CurrentUser'") or die(mysql_error());
   
   //^^ Put the user data into useable form
   $UserInfo = mysql_fetch_assoc($FindUser);
   
   //@@^^ CHECK IF Leader IS REMOVING USER ^^@@//
   if(isset($_GET['Remove']))
   {
      $RemoveInfo = explode("-", $_GET['Remove']);
      
      //Fiddle Data
      $RemoveUserID = $RemoveInfo[0];
      $RemoveFactionID = $RemoveInfo[1];
      
      //Double check the user is of privilege
      //to remove this user from the faction
      if(($UserInfo['Rank'] >= 6 && $UserInfo['Faction'] == $RemoveFactionID) || $UserInfo['id'] == $RemoveUserID)
      {   
         //Remove requested user
         $Removing = mysql_query("UPDATE users SET Faction='9999', Rank='0', RankName='None' WHERE id='$RemoveUserID'") or die(mysql_error());
      }
   }//END REMOVE USER
   
   //@@^^ CHECK IF Leaders IS INVITING USER ^^@@//
   if(isset($_GET['Inv']))
   {
      $InvInfo = explode("-", $_GET['Inv']);
      $InvUserID = $InvInfo[0];
      $InvFactionID = $InvInfo[1];
      
      //Get Users Inv Que From Db
      $InvQuery = mysql_query("SELECT FactionInv FROM users WHERE id='$InvUserID'") or die(mysql_error());;
      $InvResult = mysql_fetch_assoc($InvQuery);
      $InvQueStr = $InvResult['FactionInv'];
      
      if(empty($InvQueStr))
      {
         //No Other Invs in que
         //Add the Inv
         mysql_query("UPDATE users SET FactionInv='$InvFactionID' WHERE id='$InvUserID'") or die(mysql_error());;
      }
      else
      {
         //Other Faction Invs in que
         //Make sure this is not a repeat Inv
         $InvQue = explode('-', $InvQueStr);
         if(!(in_array($InvFactionID, $InvQue)))
         {
            //This is NOT a repeat Inv
            //Add Inv to the que
            $InvQueStr .= "-$InvFactionID";
            mysql_query("UPDATE users SET FactionInv='$InvQueStr' WHERE id='$InvUserID'") or die(mysql_error());
         }
      }
   }//END INV USER
   
   //@@^^ START CHAT BOX ^^@@//
   //Store Users Chat Information in the session
   $_SESSION['ChatUser'] = serialize($UserInfo);

   //Check If User Select a Chat Group
   if(isset($_POST['ChatID']))
   {
      $tempChatID = $_POST['ChatID'];
   }
   else if(isset($_GET['ChatID']))
   {
      $tempChatID = $_GET['ChatID'];
   }
   else
   {
      $tempChatID = 'Public';
   }
   
   //Switch from name to num
   switch($tempChatID)
   {
      case 'Leaders':
         $ChatID = '2';
      break;
      
      case 'Faction':
         $ChatID = '1';
      break;
      
      default:
         $ChatID = '0';
   }
      
   //User Made A ChatGroup Request
   //Make sure user is Leaders for Leaders chat
   if($ChatID == '2')
   {
      //User wants Leaders Chat Verify Rank
      if($UserInfo['Rank'] >= 6)
      {
         //User is Verified
         $ChatGroup = '2';
      }
      else
      {
         //User is not Leaders
         if($UserInfo['Faction'] != '9999')
         {
            //User is in a faction
            $ChatGroup = '1';
            $Output .= '<br>You are not high enough rank to view Leaders chat! Defaulted to Faction Chat.';
         }
         else
         {
            //User Not in a faction
            $ChatGroup = '0';
            $Output .= '<br>You are not in a Faction! Defaulted to Public Chat.';
         }
      }
   }
   else if($ChatID == '1')
   {
      //Make sure the user is in a faction
      //User Requesting Public/Faction Chat
      if($UserInfo['Faction'] == '9999')
      {
         //No Faction Found
         //Set to Public
         $ChatGroup = '0';
         $Output .= '<br>You are not in a Faction! Defaulted to Public Chat.';
      }
      else
      {
         //Faction Found
         //Set to Faction
         $ChatGroup = '1';
      }
   }
   else
   {
      //Set to Public
      $ChatGroup = '0';
   }
   
   //@^^ Set Member List Title
   $MEMBER_TITLE = '';
   if($UserInfo['Faction'] != '9999')
   {
      //@^^ User In A Faction
      
      //Get the Faction Names
      $UserFactionQuery = mysql_query("SELECT Name, FullName FROM factions WHERE id='".$UserInfo['Faction']."'") or die(mysql_error());
      $UserFactionResult = mysql_fetch_assoc($UserFactionQuery);
      
      //Check that ChatGroup is Faction
      if($ChatGroup == '1')
      {
         //Set Member Title to Faction FullName
         $MEMBER_TITLE = $UserFactionResult['FullName'];
      }
      else if($ChatGroup == '2')
      {
         //Set Member Title to Faction Leaders List
         $MEMBER_TITLE = "Faction Leader List";
      }
      else
      {
         //Set Member Title to Member List
         $MEMBER_TITLE = "Member List";
      }
   }
   else
   {
      //@^^ User not in A Faction
      //Set Member Title to Member List
      $MEMBER_TITLE = "Member List";
   }
   
   switch($ChatGroup)
   {
      case '2':
         //Leaders Chat
         $MEMBERS = getMembers($UserInfo, '2');
      break;
      
      case '1':
         //Faction Chat
         $MEMBERS = getMembers($UserInfo, '1');
      break;
      
      default:
         //Public Chat
         $MEMBERS = getMembers($UserInfo);         
   }
   
   //Display ChatBox
   echo <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
<meta name="description" content="description"/>
<meta name="keywords" content="keywords"/>
<meta name="author" content="author"/>
<link rel="stylesheet" type="text/css" href="default.css" media="screen"/>
<title>My Account</title>
<script type='text/javascript'>
<!--

//This function fixes a form submission bug
//where the form fields are not cleared after submission
//this bug is not isolated to one browser.
//(Browsers need an "AfterSubmit" event!)
function SubmitFix()
{
   var Form = document.getElementById('ChatForm');
   var TxtBx = document.getElementById('user_msg');
   if(Form != null && TxtBx != null)
   {//Found the Objects
      
      //@^^ Submit Form
      Form.submit();
      
      //@^^ Clear the Form
      Form.reset();
      
      //@ Return Focus To TxtBx
      TxtBx.focus();
   }
}

//This function is just a redundancy to protect
//users from accidently removing members from their faction
function confirmRemove(USER, REMOVEID, CHATID) {
   var answer = confirm("Are you sure you want to remove "+USER+" from the faction?");
   if (answer){
      window.location = "faction.php?ChatID="+CHATID+"&Remove="+REMOVEID;
   }
}

//This Function Stops the page from
//submitting when the user hit the enter key
//under normal circumstances IE handles form submissions
//properly, the chat system uses a 'targeted' submission
//and using the EnterKey doesn't work with IE in this situation.
function checkCR(evt) {

    var evt  = (evt) ? evt : ((event) ? event : null);

    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);

    if ((evt.keyCode == 13) && (node.type=="text")) {
   return false;
   }else if ((evt.keyCode == 13) && (node.type=="file")) {
    return false;
  }}

document.onkeypress = checkCR;
//-->
</script>
</head>

<!-- default margin = default layout -->
<body style="margin: 0 12%;">

<div class="container">
   <div class="header"><a href="login.php"><span>User Control Panel 1.0</span></a></div>
   
   <! -- MENU //-->
   <div class="stripes"><span></span></div>
   <div class="nav">
      <a href="myaccount.php">My Account</a>
        <a href="mylicenses.php">My Licenses</a>
        <a href="myitems.php">My Items</a>
        <a href="myskills.php">My Skills</a>
        <a href="mysettings.php">Settings</a>
        <a href="onlineplayers.php">Online Players</a>
        <a href="profile.php">Search Users</a>
      <a href="faction.php">Faction</a>
        <a href="logout.php">Logout</a>
      <div class="clearer"><span></span></div>
   </div>
   <div class="stripes"><span></span></div>
   <! -- MENU //-->
   
   <div class="main">
      <div class="center">
         <div class="content">
            <h3 class="titlehdr">Faction</h3>
            <div>{$Output}</div>
            <!-- Faction Portal //-->
            <div id='FactionWrap' style='position:relative;width:100%;height:400px;border:thin solid black;'>
               <div id='MmbrBx' style='float:left;width:25%;text-align:center;'>
                  <div style='display:table;width:100%;height:35px;'>
                     <div id='MmbrLstTtle' style='display:table-cell;vertical-align:bottom;'>
                        <span style='text-decoration:underline;font-size:x-large;font-wieght:bold;'>{$MEMBER_TITLE}</span>
                     </div>
                  </div>
                  <div id='MmbrLst' style='text-align:left;height:300px;overflow:auto;border:thin solid black;margin:0px 15px 0px 15px;padding:3px;line-height:1.5;'>
                     {$MEMBERS}
                  </div>
               </div>
               <div id='ChatBx' style='float:right;width:75%;text-align:center;overflow:hidden;'>
                  <div id='DisplayWrap'>
                     <div style='display:table;width:100%;height:35px;'>
                        <div id='ChatTabs' style='display:table-cell;width:100%;vertical-align:bottom;text-align:left;'>
                           <form action='faction.php' id='ChatBtns' method='GET' target='_self'>
                           <input type='submit' id='ChatIDPub' name='ChatID' value='Public' />
                           <input type='submit' id='ChatIDFac' name='ChatID' value='Faction' />
                           <input type='submit' id='ChatIDOff' name='ChatID' value='Leaders' />
                           </form>
                        </div>
                     </div>
                     <iframe src='chat.php?Refresh=true&ChatID={$ChatGroup}#Anchor' style='width:99%;height:300px;' id='Display' name='Display'></iframe>
                  </div>
                  <div id='TypeBx' style='position:relative;overflow:hidden;'>
                     <div id='FormWrap' style='float:left;width:50%;text-align:right;'>
                        <form action='chat.php?ChatID={$ChatGroup}#Anchor' id='ChatForm' method='POST' target='Display' >
                           Say:
                           <input style='width:90%;' type='text' id='user_msg' name='user_msg' />
                           <br>
                           <input type='button' id='Chat' name='Chat' value='Send' onclick='SubmitFix();' />
                        </form>
                     </div>
                     <div id='Menu' style='float:right;width:50%;text-align:left;'>
                        <!-- REFRESH BTN //-->
                        <form action='chat.php?ChatID={$ChatGroup}#Anchor' id='RefreshForm' method='POST' target='Display'>
                        <input type='submit' id='Refresh' name='Refresh' value='Refresh' />
                        </form>
                        <!-- REFRESH BTN //-->
                     </div>
                  </div>
               </div>
            </div>
            <!-- Faction Portal //-->
           </div>
      </div>
      <div class="clearer"><span></span></div>  
   </div>  
   <div class="footer">    
         <div class="col3">
         </div>
         <div class="bottom">          
            <span class="left">© 2010-2011 <a href="http://c-rp.net">c-rp.net</a>. Valid <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> & <a href="http://validator.w3.org/check?uri=referer">XHTML</a>.</span>
            <span class="right">Code by pbu, Efficacious, ca2k. Design by Arcsin.</span>
            <div class="clearer"><span></span></div>
         </div>
   </div>
</div>
</body>
</html>
HTML;
}
else
{
   //No User Logged In
   header("Location: login.php");
   exit();
}

?>

 

chat:

<?php
/********************** CHAT.PHP**************************
This Handles the chat display
************************************************************/
include 'dbc.php';
page_protect();

//%^^ Function to handle message gathering ^^%//
function getChat($ChatGroup, $ChatUser)
{

   //Initialize Variables
   $DELETE = null;
   $INVITES = '';
   
   //Build Inv Messages
   if(!(empty($ChatUser['FactionInv'])))
   {
      $InvQue = explode('-', $ChatUser['FactionInv']);
      $InvCount = count($InvQue);
      for($i=0;$i<$InvCount;$i++)
      {
         //Get the Faction Name Associated with the Faction ID
         $FactionNameQuery = mysql_query("SELECT Name, FullName FROM factions WHERE id='".$InvQue[$i]."'") or die(mysql_error());
         while($Faction = mysql_fetch_array($FactionNameQuery))
         {
            if($i == 0)
            {
               $INVITES .= "You have been invited to Join ".$Faction['FullName']." (".$Faction['Name']."): <a style='font-weight:bold;color:green;' href='chat.php?Refresh=true&Join=".$ChatUser['id']."-".$InvQue[$i]."-1'>Accept</a> | <a style='font-weight:bold;color:red;' href='chat.php?Refresh=true&Join=".$ChatUser['id']."-".$InvQue[$i]."-0'>Decline</a>".PHP_EOL;
            }
            else
            {
               $INVITES .= "<br>You have been invited to Join ".$Faction['FullName']." (".$Faction['Name']."): <a style='font-weight:bold;color:green;' href='chat.php?Refresh=true&Join=".$ChatUser['id']."-".$InvQue[$i]."-1'>Accept</a> | <a style='font-weight:bold;color:red;' href='chat.php?Refresh=true&Join=".$ChatUser['id']."-".$InvQue[$i]."-0'>Decline</a>".PHP_EOL;
            }
         }
      }
   }
   
   //@@^^ Switch to which chat group the user wants ^^@@//
   switch($ChatGroup)
   {
      case'2':
         //Get Only Leaders Messages
         $WHERE = "GroupID='2'";
      break;
      
      case'1':
         //Get Only Faction Messages
         $WHERE = "Faction='".$ChatUser['Faction']."' AND GroupID='1'";
      break;
      
      default:
         //Get the default chat
         $WHERE = "GroupID='0'";
   }//END SWITCH
   
   //Retrieve All Msg to post to display
   $GetMsgs = "SELECT * FROM chat WHERE $WHERE ORDER BY MsgID ASC";
   $result = mysql_query($GetMsgs) or die(mysql_error());
   while($row = mysql_fetch_array($result))
   {
      //Get the Message ID
      $MsgID = $row['MsgID'];
      
      //Check if User Rank high enough
      //to delete messages
      if($ChatUser['Rank'] >= 6)
      {
         //User is High Rank
         $DELETE = "<a style='color:red;' href='chat.php?Refresh=true&Delete=$MsgID#Anchor' target='_self'>delete</a>";
      }
      
      //Fiddle Msg Data
      $MSG = $row['Msg'];
      $MSG_AuthID = $row['UserID'];
      $MSG_Time = date("H:i:s", $row['Time']);
      $MSG_Date = $row['Date'];
   
      //@@^^ GET MSG_Auth INFO FROM DB BASED OFF $MSG_AuthID ^^@@//
      $MSG_AuthQuery = mysql_query("SELECT user_name, Faction, Rank, RankName FROM users WHERE id='$MSG_AuthID'") or die(mysql_error());
      $AuthResult = mysql_fetch_assoc($MSG_AuthQuery);
      //   $AuthResult['user_name'];
      //   $AuthResult['Faction'];
      //   $AuthResult['Rank'];
      //   $AuthResult['RankName'];
         
      //Color Code Author
      if($AuthResult['user_name'] == $ChatUser['user_name'])
      {
         //Current User sent this message
         $AUTHOR = "<span style='color:blue;'>".$AuthResult['user_name']."</span>";
      }
      else if($AuthResult['Rank'] >=6)
      {
         //User is Leaders
         //Dark Orange
         $AUTHOR = "<span style='color:red;font-weight:bold;'>".$AuthResult['user_name']."</span>";
      }
      else if($AuthResult['Faction'] == $ChatUser['Faction'])
      {
         //Msg Author is guildy of current user
         $AUTHOR = "<span style='color:green;'>".$AuthResult['user_name']."</span>";
      }
      else
      {
         //Public Member
         $AUTHOR = "<span style=''>".$AuthResult['user_name']."</span>";
      }
      
      //@@^^ Get the Name of the Authors faction ^^@@//
      //if they are in one and chat group is leaders
      if($AuthResult['Faction'] != '9999' && $ChatGroup == 2)
      {
         $FactionNameQuery = mysql_query("SELECT Name, FullName FROM factions WHERE id='$AuthFaction'") or die(mysql_error());
         $Faction = mysql_fetch_array($FactionNameQuery);
         //$Faction['Name']
         //$Faction['FullName']
         
         $FACTION = "<span style='cursor:help;' alt='".$Faction['FullName']."' title='".$Faction['FullName']."'>[".$Faction['Name']."]</span> ";
      }
      else
      {
         //Chatter is not in a Faction
         //and or User is in public chat
         $FACTION = '';
      }
      
      //Echo a messages
      echo <<<MSG
{$DELETE} <span style='cursor:help;' alt='$MSG_Date' title='$MSG_Date'>{{$MSG_Time}}</span> {$FACTION}{$AUTHOR}: {$MSG}<br>
MSG;
      echo(PHP_EOL);
   }//END MAIN LOOP
   echo("<div id='Anchor' name='Anchor'></div>".PHP_EOL);//SET PAGE ANCHOR
   echo($INVITES.PHP_EOL);
}//END getChat Function


//If user detected Compile Messages
if(isset($_SESSION['ChatUser']))
{
   //Start HTML
   echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<body style='background-color:#FFFFFF;'>
HTML;
   $ChatUser = unserialize($_SESSION['ChatUser']);
   
   //   $ChatUser['user_name'];
   //   $ChatUser['id'];
   //   $ChatUser['Rank'];
   //   $ChatUser['RankName'];
   //   $ChatUser['Faction'];
   
   //@@^^ Check If User Accepting/Joining Faction ^^@@//
   if(isset($_GET['Join']))
   {
      //Fiddle the data
      // USER - FACTION - ANSWER
      $Join = explode('-', $_GET['Join']);
      
      //Accept or Decline?
      switch($Join[2])
      {
         case '1':
            //Joining
            //Update the Users information
            mysql_query("UPDATE users SET Faction='".$Join[1]."', FactionInv=null WHERE id='".$Join[0]."'") or die(mysql_error());
            
            //Update the Sessions' ChatUser
            $ChatUser['FactionInv'] = null;
            $ChatUser['Faction'] = $Join[1];
            $_SESSION['ChatUser'] = serialize($ChatUser);
         break;
         
         default:
            //Declining
            //Get the users InvQue
            $InvQuery = mysql_query("SELECT FactionInv FROM users WHERE id='".$Join[0]."'") or die(mysql_error());
            $InvResult = mysql_fetch_assoc($InvQuery);
            $InvQueStr = $InvResult['FactionInv'];
            
            $InvQue = explode('-', $InvQueStr);
            $InvCount = count($InvQue);
            
            $NewQue = array();
            for($i=0;$i<$InvCount;$i++)
            {
               if($InvQue[$i] != $Join[1])
               {
                  //Build New Que Skipping
                  //the declined invite
                  $NewQue[] = $InvQue[$i];
               }
            }
            
            //Compact Inv Que to String for Storage
            $NewQueStr = implode('-', $NewQue);
            
            //Put the NewInvQue into the DB
            mysql_query("UPDATE users SET FactionInv='$NewQueStr' WHERE id='".$Join[0]."'") or die(mysql_error());
            
            //Update the Sessions' ChatUser
            $ChatUser['FactionInv'] = $NewQueStr;
            $_SESSION['ChatUser'] = serialize($ChatUser);
      }//END SWITCH
   }//END JOIN CHECK
   
   //@@^^ Check For A Requested Group ^^@@//
   if(isset($_POST['ChatID']))
   {
      $ChatGroup = $_POST['ChatID'];
   }
   else if(isset($_GET['ChatID']))
   {
      $ChatGroup = $_GET['ChatID'];
   }
   else
   {
      //No Request sent default to public
      $ChatGroup = '0';
   }
   
   //@@^^ Check if deleting a message ^^@@//
   if(isset($_GET['Delete']))
   {
      if($ChatUser['Rank'] >= 6)
      {
         $DeleteID = $_GET['Delete'];
         
         //Delete the message requested
         $DeleteMsg = "DELETE FROM chat WHERE MsgID='$DeleteID'";
         $DeleteQuery = mysql_query($DeleteMsg) or die(mysql_error());
      }
   }
   
   //@@^^ Check if posting a message ^^@@//
   if(!(isset($_POST['Refresh'])))
   {//NO POST REFRESH DETECTED
      
      if(!(isset($_GET['Refresh'])))
      {//NO GET REFRESH DETECTED
         $Posting = true;
      }
   }

   
   if($Posting)
   {
      $newMSG = strip_tags($_POST['user_msg']);
      $CurrentTime = time();
      $CurrentDate = date("Y-m-d");// YYYY-MM-DD
      
      //Record the Msg to the DB
      //Insert Record New Message to DB when DB is not busy
      //Helps performance in high traffic situations
      $SendMsg = "INSERT DELAYED chat (UserID, Faction, GroupID, Msg, Time, Date) VALUES ('".$ChatUser['id']."', '".$ChatUser['Faction']."', '$ChatGroup', '$newMSG', '$CurrentTime', '$CurrentDate')";
      $query = mysql_query($SendMsg) or die(mysql_error());
   }
   
   //@@^^ GET THE CHAT ^^@@//
   /*
      //DO THIS LAST!
   */
   getChat($ChatGroup, $ChatUser);
      //Finish HTML
   echo <<<HTML
</body>
</html>
HTML;
}

?>

Link to comment
https://forums.phpfreaks.com/topic/240166-internal-server-error/
Share on other sites

interestingly enough if I remove the "page_protect" function from the pages or rather just not give them a session_start() function then the files don't throw an internal server error.. so it has got to be something do with that.

 

Could the use of "serialize" and "unserialize" cause this issue?

i would love to unfortunately it isn't my server. The application works flawlessly on my server.

when i next speak with the owner of the server i will instruct him to do so but until then I'd like to exhaust any other possibilities.

the only error showing up in the logs is :

 

Premature end of script headers: faction.php

 

I did some searching on the error and found that its about as descriptive as "Internal Server Error".

 

This one has me pulling my hair out a bit... there are 4 other pages and each of those pages works just fine..

 

I compared my two pages with the other pages and I'm not doing anything special in my pages thats not being done in the others...

at least nothing that I can see.

The Premature end of script error generally means that your script did not output anything.

 

You either have a fatal parse error (since removing the session_start() statement change the symptom, a parse error is unlikely) a fatal runtime error (putting the error_reporting/display_errors settings after the first <?php tag should have shown any fatal runtime errors unless your server has output buffering turned on), or code that is not outputting anything at all.

 

For the 3rd possibility, I would start putting in echo statements to see if you can get any output and at what point in the file you can get output to occur and at what point you cannot.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.