Jump to content

Php Login, Register, Admin Cp, User Cp Script Help


ColdEdge

Recommended Posts

Hi, I am ColdEdge. I am looking for some one who could help me with modifieng a PHP script by adding few features to it such as.<!--Registration Form Add-On--!>First Name:Last Name:Location:Age: <-- if age is 10-12 then this IP is restricted from regesteringAnti-Bot: <-- something simple like math questions like 1+4=? or 10-2=?--Registration Form Hiden/Automated--IP: <-- this is an automaed prosses which will add members IP upon registration to database so if anything admin could ban this ip..Reg Date: <-- date when member has bin registed like mm, dd, yyyyDownload Credits: <-- 12 credits by defult / refreshed after 24 hours every day<!--User CP Form Add-On--!>@ The current fields are Old Password, New Password, E-Mail what I need added is the following.Credits: <-- some thing like you have "6" credits remaining -- fetch from DB -- can not be edited by member...First Name: <-- can not be edited by user just displays it in there User CPLast Name: <-- can not be edited by user just displays it in there User CPAge: <-- can not be edited by user just displays it in there User CPLocation: <-- can not be edited by user just displays it in there User CP<!--Password Recovery Form Add-On--!>@ The form asks for username but I need it to ask for the e-mail also before it can send temp passwordE-Mail: <-- requrired for security reasons before temp pass can be send<!--Admin CP Form Re-Code--!>@ Well here is the problem there is a field called Ban but instead of banding it moves member to banned_users tablefrom which you can no longer un-ban so all user info is gone... i need some one to help me fix that....Ok.... Now For The Scripts ^^Database Tables

##  dbtables.sql##  Simplifies the task of creating all the database tables#  used by the login system.##  Can be run from command prompt by typing:##  mysql -u yourusername -D yourdatabasename < dbtables.sql##  That's with dbtables.sql in the mysql bin directory, but#  you can just include the path to dbtables.sql and that's#  fine too.##  Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)#  Last Updated: August 13, 2004###  Table structure for users table#DROP TABLE IF EXISTS users;CREATE TABLE users ( username varchar(30) primary key, password varchar(32), userid varchar(32), userlevel tinyint(1) unsigned not null, email varchar(50), timestamp int(11) unsigned not null);##  Table structure for active users table#DROP TABLE IF EXISTS active_users;CREATE TABLE active_users ( username varchar(30) primary key, timestamp int(11) unsigned not null);##  Table structure for active guests table#DROP TABLE IF EXISTS active_guests;CREATE TABLE active_guests ( ip varchar(15) primary key, timestamp int(11) unsigned not null);##  Table structure for banned users table#DROP TABLE IF EXISTS banned_users;CREATE TABLE banned_users ( username varchar(30) primary key, timestamp int(11) unsigned not null);

Forgot Password

<?/** * ForgotPass.php * * This page is for those users who have forgotten their * password and want to have a new password generated for * them and sent to the email address attached to their * account in the database. The new password is not * displayed on the website for security purposes. * * Note: If your server is not properly setup to send * mail, then this page is essentially useless and it * would be better to not even link to this page from * your website. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 26, 2004 */include("include/session.php");?><html><title>Jpmaster77's Login Script</title><body><?/** * Forgot Password form has been submitted and no errors * were found with the form (the username is in the database) */if(isset($_SESSION['forgotpass'])){   /**	* New password was generated for user and sent to user's	* email address.	*/   if($_SESSION['forgotpass']){	  echo "<h1>New Password Generated</h1>";	  echo "<p>Your new password has been generated "		  ."and sent to the email <br>associated with your account. "		  ."<a href=\"main.php\">Main</a>.</p>";   }   /**	* Email could not be sent, therefore password was not	* edited in the database.	*/   else{	  echo "<h1>New Password Failure</h1>";	  echo "<p>There was an error sending you the "		  ."email with the new password,<br> so your password has not been changed. "		  ."<a href=\"main.php\">Main</a>.</p>";   }	      unset($_SESSION['forgotpass']);}else{/** * Forgot password form is displayed, if error found * it is displayed. */?><h1>Forgot Password</h1>A new password will be generated for you and sent to the email address<br>associated with your account, all you have to do is enter yourusername.<br><br><? echo $form->error("user"); ?><form action="process.php" method="POST"><b>Username:</b> <input type="text" name="user" maxlength="30" value="<? echo $form->value("user"); ?>"><input type="hidden" name="subforgot" value="1"><input type="submit" value="Get New Password"></form><?}?></body></html>

Main/Index

<?/** * Main.php * * This is an example of the main page of a website. Here * users will be able to login. However, like on most sites * the login form doesn't just have to be on the main page, * but re-appear on subsequent pages, depending on whether * the user has logged in or not. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 26, 2004 */include("include/session.php");?><html><title>Jpmaster77's Login Script</title><body><table><tr><td><?/** * User has already logged in, so display relavent links, including * a link to the admin center if the user is an administrator. */if($session->logged_in){   echo "<h1>Logged In</h1>";   echo "Welcome <b>$session->username</b>, you are logged in. <br><br>"	   ."[<a href=\"userinfo.php?user=$session->username\">My Account</a>]   "	   ."[<a href=\"useredit.php\">Edit Account</a>]   ";   if($session->isAdmin()){	  echo "[<a href=\"admin/admin.php\">Admin Center</a>]   ";   }   echo "[<a href=\"process.php\">Logout</a>]";}else{?><h1>Login</h1><?/** * User not logged in, display the login form. * If user has already tried to login, but errors were * found, display the total number of errors. * If errors occurred, they will be displayed. */if($form->num_errors > 0){   echo "<font size=\"2\" color=\"#ff0000\">".$form->num_errors." error(s) found</font>";}?><form action="process.php" method="POST"><table align="left" border="0" cellspacing="0" cellpadding="3"><tr><td>Username:</td><td><input type="text" name="user" maxlength="30" value="<? echo $form->value("user"); ?>"></td><td><? echo $form->error("user"); ?></td></tr><tr><td>Password:</td><td><input type="password" name="pass" maxlength="30" value="<? echo $form->value("pass"); ?>"></td><td><? echo $form->error("pass"); ?></td></tr><tr><td colspan="2" align="left"><input type="checkbox" name="remember" <? if($form->value("remember") != ""){ echo "checked"; } ?>><font size="2">Remember me next time     <input type="hidden" name="sublogin" value="1"><input type="submit" value="Login"></td></tr><tr><td colspan="2" align="left"><br><font size="2">[<a href="forgotpass.php">Forgot Password?</a>]</font></td><td align="right"></td></tr><tr><td colspan="2" align="left"><br>Not registered? <a href="register.php">Sign-Up!</a></td></tr></table></form><?}/** * Just a little page footer, tells how many registered members * there are, how many users currently logged in and viewing site, * and how many guests viewing site. Active users are displayed, * with link to their user information. */echo "</td></tr><tr><td align=\"center\"><br><br>";echo "<b>Member Total:</b> ".$database->getNumMembers()."<br>";echo "There are $database->num_active_users registered members and ";echo "$database->num_active_guests guests viewing the site.<br><br>";include("include/view_active.php");?></td></tr></table></body></html>

Link to comment
Share on other sites

Process

<?/** * Process.php *  * The Process class is meant to simplify the task of processing * user submitted forms, redirecting the user to the correct * pages if errors are found, or if form is successful, either * way. Also handles the logout procedure. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */include("include/session.php");class Process{   /* Class constructor */   function Process(){	  global $session;	  /* User submitted login form */	  if(isset($_POST['sublogin'])){		 $this->procLogin();	  }	  /* User submitted registration form */	  else if(isset($_POST['subjoin'])){		 $this->procRegister();	  }	  /* User submitted forgot password form */	  else if(isset($_POST['subforgot'])){		 $this->procForgotPass();	  }	  /* User submitted edit account form */	  else if(isset($_POST['subedit'])){		 $this->procEditAccount();	  }	  /**	   * The only other reason user should be directed here	   * is if he wants to logout, which means user is	   * logged in currently.	   */	  else if($session->logged_in){		 $this->procLogout();	  }	  /**	   * Should not get here, which means user is viewing this page	   * by mistake and therefore is redirected.	   */	   else{		  header("Location: main.php");	   }   }   /**	* procLogin - Processes the user submitted login form, if errors	* are found, the user is redirected to correct the information,	* if not, the user is effectively logged in to the system.	*/   function procLogin(){	  global $session, $form;	  /* Login attempt */	  $retval = $session->login($_POST['user'], $_POST['pass'], isset($_POST['remember']));	  	  /* Login successful */	  if($retval){		 header("Location: ".$session->referrer);	  }	  /* Login failed */	  else{		 $_SESSION['value_array'] = $_POST;		 $_SESSION['error_array'] = $form->getErrorArray();		 header("Location: ".$session->referrer);	  }   }      /**	* procLogout - Simply attempts to log the user out of the system	* given that there is no logout form to process.	*/   function procLogout(){	  global $session;	  $retval = $session->logout();	  header("Location: main.php");   }      /**	* procRegister - Processes the user submitted registration form,	* if errors are found, the user is redirected to correct the	* information, if not, the user is effectively registered with	* the system and an email is (optionally) sent to the newly	* created user.	*/   function procRegister(){	  global $session, $form;	  /* Convert username to all lowercase (by option) */	  if(ALL_LOWERCASE){		 $_POST['user'] = strtolower($_POST['user']);	  }	  /* Registration attempt */	  $retval = $session->register($_POST['user'], $_POST['pass'], $_POST['email']);	  	  /* Registration Successful */	  if($retval == 0){		 $_SESSION['reguname'] = $_POST['user'];		 $_SESSION['regsuccess'] = true;		 header("Location: ".$session->referrer);	  }	  /* Error found with form */	  else if($retval == 1){		 $_SESSION['value_array'] = $_POST;		 $_SESSION['error_array'] = $form->getErrorArray();		 header("Location: ".$session->referrer);	  }	  /* Registration attempt failed */	  else if($retval == 2){		 $_SESSION['reguname'] = $_POST['user'];		 $_SESSION['regsuccess'] = false;		 header("Location: ".$session->referrer);	  }   }      /**	* procForgotPass - Validates the given username then if	* everything is fine, a new password is generated and	* emailed to the address the user gave on sign up.	*/   function procForgotPass(){	  global $database, $session, $mailer, $form;	  /* Username error checking */	  $subuser = $_POST['user'];	  $field = "user";  //Use field name for username	  if(!$subuser || strlen($subuser = trim($subuser)) == 0){		 $form->setError($field, "* Username not entered<br>");	  }	  else{		 /* Make sure username is in database */		 $subuser = stripslashes($subuser);		 if(strlen($subuser) < 5 || strlen($subuser) > 30 ||			!eregi("^([0-9a-z])+$", $subuser) ||			(!$database->usernameTaken($subuser))){			$form->setError($field, "* Username does not exist<br>");		 }	  }	  	  /* Errors exist, have user correct them */	  if($form->num_errors > 0){		 $_SESSION['value_array'] = $_POST;		 $_SESSION['error_array'] = $form->getErrorArray();	  }	  /* Generate new password and email it to user */	  else{		 /* Generate new password */		 $newpass = $session->generateRandStr(8);		 		 /* Get email of user */		 $usrinf = $database->getUserInfo($subuser);		 $email  = $usrinf['email'];		 		 /* Attempt to send the email with new password */		 if($mailer->sendNewPass($subuser,$email,$newpass)){			/* Email sent, update database */			$database->updateUserField($subuser, "password", md5($newpass));			$_SESSION['forgotpass'] = true;		 }		 /* Email failure, do not change password */		 else{			$_SESSION['forgotpass'] = false;		 }	  }	  	  header("Location: ".$session->referrer);   }      /**	* procEditAccount - Attempts to edit the user's account	* information, including the password, which must be verified	* before a change is made.	*/   function procEditAccount(){	  global $session, $form;	  /* Account edit attempt */	  $retval = $session->editAccount($_POST['curpass'], $_POST['newpass'], $_POST['email']);	  /* Account edit successful */	  if($retval){		 $_SESSION['useredit'] = true;		 header("Location: ".$session->referrer);	  }	  /* Error found with form */	  else{		 $_SESSION['value_array'] = $_POST;		 $_SESSION['error_array'] = $form->getErrorArray();		 header("Location: ".$session->referrer);	  }   }};/* Initialize process */$process = new Process;?>

Register

<?/** * Register.php *  * Displays the registration form if the user needs to sign-up, * or lets the user know, if he's already logged in, that he * can't register another name. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */include("include/session.php");?><html><title>Registration Page</title><body><?/** * The user is already logged in, not allowed to register. */if($session->logged_in){   echo "<h1>Registered</h1>";   echo "<p>We're sorry <b>$session->username</b>, but you've already registered. "	   ."<a href=\"main.php\">Main</a>.</p>";}/** * The user has submitted the registration form and the * results have been processed. */else if(isset($_SESSION['regsuccess'])){   /* Registration was successful */   if($_SESSION['regsuccess']){	  echo "<h1>Registered!</h1>";	  echo "<p>Thank you <b>".$_SESSION['reguname']."</b>, your information has been added to the database, "		  ."you may now <a href=\"main.php\">log in</a>.</p>";   }   /* Registration failed */   else{	  echo "<h1>Registration Failed</h1>";	  echo "<p>We're sorry, but an error has occurred and your registration for the username <b>".$_SESSION['reguname']."</b>, "		  ."could not be completed.<br>Please try again at a later time.</p>";   }   unset($_SESSION['regsuccess']);   unset($_SESSION['reguname']);}/** * The user has not filled out the registration form yet. * Below is the page with the sign-up form, the names * of the input fields are important and should not * be changed. */else{?><h1>Register</h1><?if($form->num_errors > 0){   echo "<td><font size=\"2\" color=\"#ff0000\">".$form->num_errors." error(s) found</font></td>";}?><form action="process.php" method="POST"><table align="left" border="0" cellspacing="0" cellpadding="3"><tr><td>Username:</td><td><input type="text" name="user" maxlength="30" value="<? echo $form->value("user"); ?>"></td><td><? echo $form->error("user"); ?></td></tr><tr><td>Password:</td><td><input type="password" name="pass" maxlength="30" value="<? echo $form->value("pass"); ?>"></td><td><? echo $form->error("pass"); ?></td></tr><tr><td>Email:</td><td><input type="text" name="email" maxlength="50" value="<? echo $form->value("email"); ?>"></td><td><? echo $form->error("email"); ?></td></tr><tr><td colspan="2" align="right"><input type="hidden" name="subjoin" value="1"><input type="submit" value="Join!"></td></tr><tr><td colspan="2" align="left"><a href="main.php">Back to Main</a></td></tr></table></form><?}?></body></html>

User CP

<?/** * UserEdit.php * * This page is for users to edit their account information * such as their password, email address, etc. Their * usernames can not be edited. When changing their * password, they must first confirm their current password. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 26, 2004 */include("include/session.php");?><html><title>Jpmaster77's Login Script</title><body><?/** * User has submitted form without errors and user's * account has been edited successfully. */if(isset($_SESSION['useredit'])){   unset($_SESSION['useredit']);      echo "<h1>User Account Edit Success!</h1>";   echo "<p><b>$session->username</b>, your account has been successfully updated. "	   ."<a href=\"main.php\">Main</a>.</p>";}else{?><?/** * If user is not logged in, then do not display anything. * If user is logged in, then display the form to edit * account information, with the current email address * already in the field. */if($session->logged_in){?><h1>User Account Edit : <? echo $session->username; ?></h1><?if($form->num_errors > 0){   echo "<td><font size=\"2\" color=\"#ff0000\">".$form->num_errors." error(s) found</font></td>";}?><form action="process.php" method="POST"><table align="left" border="0" cellspacing="0" cellpadding="3"><tr><td>Current Password:</td><td><input type="password" name="curpass" maxlength="30" value="<?echo $form->value("curpass"); ?>"></td><td><? echo $form->error("curpass"); ?></td></tr><tr><td>New Password:</td><td><input type="password" name="newpass" maxlength="30" value="<? echo $form->value("newpass"); ?>"></td><td><? echo $form->error("newpass"); ?></td></tr><tr><td>Email:</td><td><input type="text" name="email" maxlength="50" value="<?if($form->value("email") == ""){   echo $session->userinfo['email'];}else{   echo $form->value("email");}?>"></td><td><? echo $form->error("email"); ?></td></tr><tr><td colspan="2" align="right"><input type="hidden" name="subedit" value="1"><input type="submit" value="Edit Account"></td></tr><tr><td colspan="2" align="left"></td></tr></table></form><?}}?></body></html>

User Info

<?/** * UserInfo.php * * This page is for users to view their account information * with a link added for them to edit the information. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 26, 2004 */include("include/session.php");?><html><title>Jpmaster77's Login Script</title><body><?/* Requested Username error checking */$req_user = trim($_GET['user']);if(!$req_user || strlen($req_user) == 0 ||   !eregi("^([0-9a-z])+$", $req_user) ||   !$database->usernameTaken($req_user)){   die("Username not registered");}/* Logged in user viewing own account */if(strcmp($session->username,$req_user) == 0){   echo "<h1>My Account</h1>";}/* Visitor not viewing own account */else{   echo "<h1>User Info</h1>";}/* Display requested user information */$req_user_info = $database->getUserInfo($req_user);/* Username */echo "<b>Username: ".$req_user_info['username']."</b><br>";/* Email */echo "<b>Email:</b> ".$req_user_info['email']."<br>";/** * Note: when you add your own fields to the users table * to hold more information, like homepage, location, etc. * they can be easily accessed by the user info array. * * $session->user_info['location']; (for logged in users) * * ..and for this page, * * $req_user_info['location']; (for any user) *//* If logged in user viewing own account, give link to edit */if(strcmp($session->username,$req_user) == 0){   echo "<br><a href=\"useredit.php\">Edit Account Information</a><br>";}/* Link back to main */echo "<br>Back To [<a href=\"main.php\">Main</a>]<br>";?></body></html>

Link to comment
Share on other sites

Admin CP

<?/** * Admin.php * * This is the Admin Center page. Only administrators * are allowed to view this page. This page displays the * database table of users and banned users. Admins can * choose to delete specific users, delete inactive users, * ban users, update user levels, etc. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 26, 2004 */include("../include/session.php");/** * displayUsers - Displays the users database table in * a nicely formatted html table. */function displayUsers(){   global $database;   $q = "SELECT username,userlevel,email,timestamp "	   ."FROM ".TBL_USERS." ORDER BY userlevel DESC,username";   $result = $database->query($q);   /* Error occurred, return given name by default */   $num_rows = mysql_numrows($result);   if(!$result || ($num_rows < 0)){	  echo "Error displaying info";	  return;   }   if($num_rows == 0){	  echo "Database table empty";	  return;   }   /* Display table contents */   echo "<table align=\"left\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n";   echo "<tr><td><b>Username</b></td><td><b>Level</b></td><td><b>Email</b></td><td><b>Last Active</b></td></tr>\n";   for($i=0; $i<$num_rows; $i++){	  $uname  = mysql_result($result,$i,"username");	  $ulevel = mysql_result($result,$i,"userlevel");	  $email  = mysql_result($result,$i,"email");	  $time   = mysql_result($result,$i,"timestamp");	  echo "<tr><td>$uname</td><td>$ulevel</td><td>$email</td><td>$time</td></tr>\n";   }   echo "</table><br>\n";}/** * displayBannedUsers - Displays the banned users * database table in a nicely formatted html table. */function displayBannedUsers(){   global $database;   $q = "SELECT username,timestamp "	   ."FROM ".TBL_BANNED_USERS." ORDER BY username";   $result = $database->query($q);   /* Error occurred, return given name by default */   $num_rows = mysql_numrows($result);   if(!$result || ($num_rows < 0)){	  echo "Error displaying info";	  return;   }   if($num_rows == 0){	  echo "Database table empty";	  return;   }   /* Display table contents */   echo "<table align=\"left\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n";   echo "<tr><td><b>Username</b></td><td><b>Time Banned</b></td></tr>\n";   for($i=0; $i<$num_rows; $i++){	  $uname = mysql_result($result,$i,"username");	  $time  = mysql_result($result,$i,"timestamp");	  echo "<tr><td>$uname</td><td>$time</td></tr>\n";   }   echo "</table><br>\n";}   /** * User not an administrator, redirect to main page * automatically. */if(!$session->isAdmin()){   header("Location: ../main.php");}else{/** * Administrator is viewing page, so display all * forms. */?><html><title>Jpmaster77's Login Script</title><body><h1>Admin Center</h1><font size="5" color="#ff0000"><b>::::::::::::::::::::::::::::::::::::::::::::</b></font><font size="4">Logged in as <b><? echo $session->username; ?></b></font><br><br>Back to [<a href="../main.php">Main Page</a>]<br><br><?if($form->num_errors > 0){   echo "<font size=\"4\" color=\"#ff0000\">"	   ."!*** Error with request, please fix</font><br><br>";}?><table align="left" border="0" cellspacing="5" cellpadding="5"><tr><td><?/** * Display Users Table */?><h3>Users Table Contents:</h3><?displayUsers();?></td></tr><tr><td><br><?/** * Update User Level */?><h3>Update User Level</h3><? echo $form->error("upduser"); ?><table><form action="adminprocess.php" method="POST"><tr><td>Username:<br><input type="text" name="upduser" maxlength="30" value="<? echo $form->value("upduser"); ?>"></td><td>Level:<br><select name="updlevel"><option value="1">1<option value="9">9</select></td><td><br><input type="hidden" name="subupdlevel" value="1"><input type="submit" value="Update Level"></td></tr></form></table></td></tr><tr><td><hr></td></tr><tr><td><?/** * Delete User */?><h3>Delete User</h3><? echo $form->error("deluser"); ?><form action="adminprocess.php" method="POST">Username:<br><input type="text" name="deluser" maxlength="30" value="<? echo $form->value("deluser"); ?>"><input type="hidden" name="subdeluser" value="1"><input type="submit" value="Delete User"></form></td></tr><tr><td><hr></td></tr><tr><td><?/** * Delete Inactive Users */?><h3>Delete Inactive Users</h3>This will delete all users (not administrators), who have not logged in to the site<br>within a certain time period. You specify the days spent inactive.<br><br><table><form action="adminprocess.php" method="POST"><tr><td>Days:<br><select name="inactdays"><option value="3">3<option value="7">7<option value="14">14<option value="30">30<option value="100">100<option value="365">365</select></td><td><br><input type="hidden" name="subdelinact" value="1"><input type="submit" value="Delete All Inactive"></td></form></table></td></tr><tr><td><hr></td></tr><tr><td><?/** * Ban User */?><h3>Ban User</h3><? echo $form->error("banuser"); ?><form action="adminprocess.php" method="POST">Username:<br><input type="text" name="banuser" maxlength="30" value="<? echo $form->value("banuser"); ?>"><input type="hidden" name="subbanuser" value="1"><input type="submit" value="Ban User"></form></td></tr><tr><td><hr></td></tr><tr><td><?/** * Display Banned Users Table */?><h3>Banned Users Table Contents:</h3><?displayBannedUsers();?></td></tr><tr><td><hr></td></tr><tr><td><?/** * Delete Banned User */?><h3>Delete Banned User</h3><? echo $form->error("delbanuser"); ?><form action="adminprocess.php" method="POST">Username:<br><input type="text" name="delbanuser" maxlength="30" value="<? echo $form->value("delbanuser"); ?>"><input type="hidden" name="subdelbanned" value="1"><input type="submit" value="Delete Banned User"></form></td></tr></table></body></html><?}?>

Admin Process

<?/** * AdminProcess.php *  * The AdminProcess class is meant to simplify the task of processing * admin submitted forms from the admin center, these deal with * member system adjustments. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 15, 2004 */include("../include/session.php");class AdminProcess{   /* Class constructor */   function AdminProcess(){	  global $session;	  /* Make sure administrator is accessing page */	  if(!$session->isAdmin()){		 header("Location: ../main.php");		 return;	  }	  /* Admin submitted update user level form */	  if(isset($_POST['subupdlevel'])){		 $this->procUpdateLevel();	  }	  /* Admin submitted delete user form */	  else if(isset($_POST['subdeluser'])){		 $this->procDeleteUser();	  }	  /* Admin submitted delete inactive users form */	  else if(isset($_POST['subdelinact'])){		 $this->procDeleteInactive();	  }	  /* Admin submitted ban user form */	  else if(isset($_POST['subbanuser'])){		 $this->procBanUser();	  }	  /* Admin submitted delete banned user form */	  else if(isset($_POST['subdelbanned'])){		 $this->procDeleteBannedUser();	  }	  /* Should not get here, redirect to home page */	  else{		 header("Location: ../main.php");	  }   }   /**	* procUpdateLevel - If the submitted username is correct,	* their user level is updated according to the admin's	* request.	*/   function procUpdateLevel(){	  global $session, $database, $form;	  /* Username error checking */	  $subuser = $this->checkUsername("upduser");	  	  /* Errors exist, have user correct them */	  if($form->num_errors > 0){		 $_SESSION['value_array'] = $_POST;		 $_SESSION['error_array'] = $form->getErrorArray();		 header("Location: ".$session->referrer);	  }	  /* Update user level */	  else{		 $database->updateUserField($subuser, "userlevel", (int)$_POST['updlevel']);		 header("Location: ".$session->referrer);	  }   }      /**	* procDeleteUser - If the submitted username is correct,	* the user is deleted from the database.	*/   function procDeleteUser(){	  global $session, $database, $form;	  /* Username error checking */	  $subuser = $this->checkUsername("deluser");	  	  /* Errors exist, have user correct them */	  if($form->num_errors > 0){		 $_SESSION['value_array'] = $_POST;		 $_SESSION['error_array'] = $form->getErrorArray();		 header("Location: ".$session->referrer);	  }	  /* Delete user from database */	  else{		 $q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";		 $database->query($q);		 header("Location: ".$session->referrer);	  }   }      /**	* procDeleteInactive - All inactive users are deleted from	* the database, not including administrators. Inactivity	* is defined by the number of days specified that have	* gone by that the user has not logged in.	*/   function procDeleteInactive(){	  global $session, $database;	  $inact_time = $session->time - $_POST['inactdays']*24*60*60;	  $q = "DELETE FROM ".TBL_USERS." WHERE timestamp < $inact_time "		  ."AND userlevel != ".ADMIN_LEVEL;	  $database->query($q);	  header("Location: ".$session->referrer);   }      /**	* procBanUser - If the submitted username is correct,	* the user is banned from the member system, which entails	* removing the username from the users table and adding	* it to the banned users table.	*/   function procBanUser(){	  global $session, $database, $form;	  /* Username error checking */	  $subuser = $this->checkUsername("banuser");	  	  /* Errors exist, have user correct them */	  if($form->num_errors > 0){		 $_SESSION['value_array'] = $_POST;		 $_SESSION['error_array'] = $form->getErrorArray();		 header("Location: ".$session->referrer);	  }	  /* Ban user from member system */	  else{		 $q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";		 $database->query($q);		 $q = "INSERT INTO ".TBL_BANNED_USERS." VALUES ('$subuser', $session->time)";		 $database->query($q);		 header("Location: ".$session->referrer);	  }   }      /**	* procDeleteBannedUser - If the submitted username is correct,	* the user is deleted from the banned users table, which	* enables someone to register with that username again.	*/   function procDeleteBannedUser(){	  global $session, $database, $form;	  /* Username error checking */	  $subuser = $this->checkUsername("delbanuser", true);	  	  /* Errors exist, have user correct them */	  if($form->num_errors > 0){		 $_SESSION['value_array'] = $_POST;		 $_SESSION['error_array'] = $form->getErrorArray();		 header("Location: ".$session->referrer);	  }	  /* Delete user from database */	  else{		 $q = "DELETE FROM ".TBL_BANNED_USERS." WHERE username = '$subuser'";		 $database->query($q);		 header("Location: ".$session->referrer);	  }   }      /**	* checkUsername - Helper function for the above processing,	* it makes sure the submitted username is valid, if not,	* it adds the appropritate error to the form.	*/   function checkUsername($uname, $ban=false){	  global $database, $form;	  /* Username error checking */	  $subuser = $_POST[$uname];	  $field = $uname;  //Use field name for username	  if(!$subuser || strlen($subuser = trim($subuser)) == 0){		 $form->setError($field, "* Username not entered<br>");	  }	  else{		 /* Make sure username is in database */		 $subuser = stripslashes($subuser);		 if(strlen($subuser) < 5 || strlen($subuser) > 30 ||			!eregi("^([0-9a-z])+$", $subuser) ||			(!$ban && !$database->usernameTaken($subuser))){			$form->setError($field, "* Username does not exist<br>");		 }	  }	  return $subuser;   }};/* Initialize process */$adminprocess = new AdminProcess;?>

Constant

<?/** * Constants.php * * This file is intended to group all constants to * make it easier for the site administrator to tweak * the login script. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ /** * Database Constants - these constants are required * in order for there to be a successful connection * to the MySQL database. Make sure the information is * correct. */define("DB_SERVER", "localhost");define("DB_USER", "your_name");define("DB_PASS", "your_pass");define("DB_NAME", "your_dbname");/** * Database Table Constants - these constants * hold the names of all the database tables used * in the script. */define("TBL_USERS", "users");define("TBL_ACTIVE_USERS",  "active_users");define("TBL_ACTIVE_GUESTS", "active_guests");define("TBL_BANNED_USERS",  "banned_users");/** * Special Names and Level Constants - the admin * page will only be accessible to the user with * the admin name and also to those users at the * admin user level. Feel free to change the names * and level constants as you see fit, you may * also add additional level specifications. * Levels must be digits between 0-9. */define("ADMIN_NAME", "admin");define("GUEST_NAME", "Guest");define("ADMIN_LEVEL", 9);define("USER_LEVEL",  1);define("GUEST_LEVEL", 0);/** * This boolean constant controls whether or * not the script keeps track of active users * and active guests who are visiting the site. */define("TRACK_VISITORS", true);/** * Timeout Constants - these constants refer to * the maximum amount of time (in minutes) after * their last page fresh that a user and guest * are still considered active visitors. */define("USER_TIMEOUT", 10);define("GUEST_TIMEOUT", 5);/** * Cookie Constants - these are the parameters * to the setcookie function call, change them * if necessary to fit your website. If you need * help, visit www.php.net for more info. * <http://www.php.net/manual/en/function.setcookie.php> */define("COOKIE_EXPIRE", 60*60*24*100);  //100 days by defaultdefine("COOKIE_PATH", "/");  //Avaible in whole domain/** * Email Constants - these specify what goes in * the from field in the emails that the script * sends to users, and whether to send a * welcome email to newly registered users. */define("EMAIL_FROM_NAME", "YourName");define("EMAIL_FROM_ADDR", "youremail@address.com");define("EMAIL_WELCOME", false);/** * This constant forces all users to have * lowercase usernames, capital letters are * converted automatically. */define("ALL_LOWERCASE", false);?>

Database

<?/** * Database.php *  * The Database class is meant to simplify the task of accessing * information from the website's database. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 17, 2004 */include("constants.php");	  class MySQLDB{   var $connection;		 //The MySQL database connection   var $num_active_users;   //Number of active users viewing site   var $num_active_guests;  //Number of active guests viewing site   var $num_members;		//Number of signed-up users   /* Note: call getNumMembers() to access $num_members! */   /* Class constructor */   function MySQLDB(){	  /* Make connection to database */	  $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());	  mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());	  	  /**	   * Only query database to find out number of members	   * when getNumMembers() is called for the first time,	   * until then, default value set.	   */	  $this->num_members = -1;	  	  if(TRACK_VISITORS){		 /* Calculate number of users at site */		 $this->calcNumActiveUsers();	  		 /* Calculate number of guests at site */		 $this->calcNumActiveGuests();	  }   }   /**	* confirmUserPass - Checks whether or not the given	* username is in the database, if so it checks if the	* given password is the same password in the database	* for that user. If the user doesn't exist or if the	* passwords don't match up, it returns an error code	* (1 or 2). On success it returns 0.	*/   function confirmUserPass($username, $password){	  /* Add slashes if necessary (for query) */	  if(!get_magic_quotes_gpc()) {		  $username = addslashes($username);	  }	  /* Verify that user is in database */	  $q = "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";	  $result = mysql_query($q, $this->connection);	  if(!$result || (mysql_numrows($result) < 1)){		 return 1; //Indicates username failure	  }	  /* Retrieve password from result, strip slashes */	  $dbarray = mysql_fetch_array($result);	  $dbarray['password'] = stripslashes($dbarray['password']);	  $password = stripslashes($password);	  /* Validate that password is correct */	  if($password == $dbarray['password']){		 return 0; //Success! Username and password confirmed	  }	  else{		 return 2; //Indicates password failure	  }   }      /**	* confirmUserID - Checks whether or not the given	* username is in the database, if so it checks if the	* given userid is the same userid in the database	* for that user. If the user doesn't exist or if the	* userids don't match up, it returns an error code	* (1 or 2). On success it returns 0.	*/   function confirmUserID($username, $userid){	  /* Add slashes if necessary (for query) */	  if(!get_magic_quotes_gpc()) {		  $username = addslashes($username);	  }	  /* Verify that user is in database */	  $q = "SELECT userid FROM ".TBL_USERS." WHERE username = '$username'";	  $result = mysql_query($q, $this->connection);	  if(!$result || (mysql_numrows($result) < 1)){		 return 1; //Indicates username failure	  }	  /* Retrieve userid from result, strip slashes */	  $dbarray = mysql_fetch_array($result);	  $dbarray['userid'] = stripslashes($dbarray['userid']);	  $userid = stripslashes($userid);	  /* Validate that userid is correct */	  if($userid == $dbarray['userid']){		 return 0; //Success! Username and userid confirmed	  }	  else{		 return 2; //Indicates userid invalid	  }   }      /**	* usernameTaken - Returns true if the username has	* been taken by another user, false otherwise.	*/   function usernameTaken($username){	  if(!get_magic_quotes_gpc()){		 $username = addslashes($username);	  }	  $q = "SELECT username FROM ".TBL_USERS." WHERE username = '$username'";	  $result = mysql_query($q, $this->connection);	  return (mysql_numrows($result) > 0);   }      /**	* usernameBanned - Returns true if the username has	* been banned by the administrator.	*/   function usernameBanned($username){	  if(!get_magic_quotes_gpc()){		 $username = addslashes($username);	  }	  $q = "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = '$username'";	  $result = mysql_query($q, $this->connection);	  return (mysql_numrows($result) > 0);   }      /**	* addNewUser - Inserts the given (username, password, email)	* info into the database. Appropriate user level is set.	* Returns true on success, false otherwise.	*/   function addNewUser($username, $password, $email){	  $time = time();	  /* If admin sign up, give admin user level */	  if(strcasecmp($username, ADMIN_NAME) == 0){		 $ulevel = ADMIN_LEVEL;	  }else{		 $ulevel = USER_LEVEL;	  }	  $q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password', '0', $ulevel, '$email', $time)";	  return mysql_query($q, $this->connection);   }      /**	* updateUserField - Updates a field, specified by the field	* parameter, in the user's row of the database.	*/   function updateUserField($username, $field, $value){	  $q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'";	  return mysql_query($q, $this->connection);   }      /**	* getUserInfo - Returns the result array from a mysql	* query asking for all information stored regarding	* the given username. If query fails, NULL is returned.	*/   function getUserInfo($username){	  $q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";	  $result = mysql_query($q, $this->connection);	  /* Error occurred, return given name by default */	  if(!$result || (mysql_numrows($result) < 1)){		 return NULL;	  }	  /* Return result array */	  $dbarray = mysql_fetch_array($result);	  return $dbarray;   }      /**	* getNumMembers - Returns the number of signed-up users	* of the website, banned members not included. The first	* time the function is called on page load, the database	* is queried, on subsequent calls, the stored result	* is returned. This is to improve efficiency, effectively	* not querying the database when no call is made.	*/   function getNumMembers(){	  if($this->num_members < 0){		 $q = "SELECT * FROM ".TBL_USERS;		 $result = mysql_query($q, $this->connection);		 $this->num_members = mysql_numrows($result);	  }	  return $this->num_members;   }      /**	* calcNumActiveUsers - Finds out how many active users	* are viewing site and sets class variable accordingly.	*/   function calcNumActiveUsers(){	  /* Calculate number of users at site */	  $q = "SELECT * FROM ".TBL_ACTIVE_USERS;	  $result = mysql_query($q, $this->connection);	  $this->num_active_users = mysql_numrows($result);   }      /**	* calcNumActiveGuests - Finds out how many active guests	* are viewing site and sets class variable accordingly.	*/   function calcNumActiveGuests(){	  /* Calculate number of guests at site */	  $q = "SELECT * FROM ".TBL_ACTIVE_GUESTS;	  $result = mysql_query($q, $this->connection);	  $this->num_active_guests = mysql_numrows($result);   }      /**	* addActiveUser - Updates username's last active timestamp	* in the database, and also adds him to the table of	* active users, or updates timestamp if already there.	*/   function addActiveUser($username, $time){	  $q = "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'";	  mysql_query($q, $this->connection);	  	  if(!TRACK_VISITORS) return;	  $q = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')";	  mysql_query($q, $this->connection);	  $this->calcNumActiveUsers();   }      /* addActiveGuest - Adds guest to active guests table */   function addActiveGuest($ip, $time){	  if(!TRACK_VISITORS) return;	  $q = "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ('$ip', '$time')";	  mysql_query($q, $this->connection);	  $this->calcNumActiveGuests();   }      /* These functions are self explanatory, no need for comments */      /* removeActiveUser */   function removeActiveUser($username){	  if(!TRACK_VISITORS) return;	  $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = '$username'";	  mysql_query($q, $this->connection);	  $this->calcNumActiveUsers();   }      /* removeActiveGuest */   function removeActiveGuest($ip){	  if(!TRACK_VISITORS) return;	  $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'";	  mysql_query($q, $this->connection);	  $this->calcNumActiveGuests();   }      /* removeInactiveUsers */   function removeInactiveUsers(){	  if(!TRACK_VISITORS) return;	  $timeout = time()-USER_TIMEOUT*60;	  $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout";	  mysql_query($q, $this->connection);	  $this->calcNumActiveUsers();   }   /* removeInactiveGuests */   function removeInactiveGuests(){	  if(!TRACK_VISITORS) return;	  $timeout = time()-GUEST_TIMEOUT*60;	  $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout";	  mysql_query($q, $this->connection);	  $this->calcNumActiveGuests();   }      /**	* query - Performs the given query on the database and	* returns the result, which may be false, true or a	* resource identifier.	*/   function query($query){	  return mysql_query($query, $this->connection);   }};/* Create database connection */$database = new MySQLDB;?>

Form

<? /** * Form.php * * The Form class is meant to simplify the task of keeping * track of errors in user submitted forms and the form * field values that were entered correctly. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ class Form{   var $values = array();  //Holds submitted form field values   var $errors = array();  //Holds submitted form error messages   var $num_errors;   //The number of errors in submitted form   /* Class constructor */   function Form(){	  /**	   * Get form value and error arrays, used when there	   * is an error with a user-submitted form.	   */	  if(isset($_SESSION['value_array']) && isset($_SESSION['error_array'])){		 $this->values = $_SESSION['value_array'];		 $this->errors = $_SESSION['error_array'];		 $this->num_errors = count($this->errors);		 unset($_SESSION['value_array']);		 unset($_SESSION['error_array']);	  }	  else{		 $this->num_errors = 0;	  }   }   /**	* setValue - Records the value typed into the given	* form field by the user.	*/   function setValue($field, $value){	  $this->values[$field] = $value;   }   /**	* setError - Records new form error given the form	* field name and the error message attached to it.	*/   function setError($field, $errmsg){	  $this->errors[$field] = $errmsg;	  $this->num_errors = count($this->errors);   }   /**	* value - Returns the value attached to the given	* field, if none exists, the empty string is returned.	*/   function value($field){	  if(array_key_exists($field,$this->values)){		 return htmlspecialchars(stripslashes($this->values[$field]));	  }else{		 return "";	  }   }   /**	* error - Returns the error message attached to the	* given field, if none exists, the empty string is returned.	*/   function error($field){	  if(array_key_exists($field,$this->errors)){		 return "<font size=\"2\" color=\"#ff0000\">".$this->errors[$field]."</font>";	  }else{		 return "";	  }   }   /* getErrorArray - Returns the array of error messages */   function getErrorArray(){	  return $this->errors;   }}; ?>

Link to comment
Share on other sites

Mailer

<? /** * Mailer.php * * The Mailer class is meant to simplify the task of sending * emails to users. Note: this email system will not work * if your server is not setup to send mail. * * If you are running Windows and want a mail server, check * out this website to see a list of freeware programs: * <http://www.snapfiles.com/freeware/server/fwmailserver.html> * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ class Mailer{   /**	* sendWelcome - Sends a welcome message to the newly	* registered user, also supplying the username and	* password.	*/   function sendWelcome($user, $email, $pass){	  $from = "From: ".EMAIL_FROM_NAME." <".EMAIL_FROM_ADDR.">";	  $subject = "Jpmaster77's Site - Welcome!";	  $body = $user.",\n\n"			 ."Welcome! You've just registered at Jpmaster77's Site "			 ."with the following information:\n\n"			 ."Username: ".$user."\n"			 ."Password: ".$pass."\n\n"			 ."If you ever lose or forget your password, a new "			 ."password will be generated for you and sent to this "			 ."email address, if you would like to change your "			 ."email address you can do so by going to the "			 ."My Account page after signing in.\n\n"			 ."- Jpmaster77's Site";	  return mail($email,$subject,$body,$from);   }      /**	* sendNewPass - Sends the newly generated password	* to the user's email address that was specified at	* sign-up.	*/   function sendNewPass($user, $email, $pass){	  $from = "From: ".EMAIL_FROM_NAME." <".EMAIL_FROM_ADDR.">";	  $subject = "Jpmaster77's Site - Your new password";	  $body = $user.",\n\n"			 ."We've generated a new password for you at your "			 ."request, you can use this new password with your "			 ."username to log in to Jpmaster77's Site.\n\n"			 ."Username: ".$user."\n"			 ."New Password: ".$pass."\n\n"			 ."It is recommended that you change your password "			 ."to something that is easier to remember, which "			 ."can be done by going to the My Account page "			 ."after signing in.\n\n"			 ."- Jpmaster77's Site";			 	  return mail($email,$subject,$body,$from);   }};/* Initialize mailer object */$mailer = new Mailer; ?>

Session

<?/** * Session.php *  * The Session class is meant to simplify the task of keeping * track of logged in users and also guests. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */include("database.php");include("mailer.php");include("form.php");class Session{   var $username;	 //Username given on sign-up   var $userid;	   //Random value generated on current login   var $userlevel;	//The level to which the user pertains   var $time;		 //Time user was last active (page loaded)   var $logged_in;	//True if user is logged in, false otherwise   var $userinfo = array();  //The array holding all user info   var $url;		  //The page url current being viewed   var $referrer;	 //Last recorded site page viewed   /**	* Note: referrer should really only be considered the actual	* page referrer in process.php, any other time it may be	* inaccurate.	*/   /* Class constructor */   function Session(){	  $this->time = time();	  $this->startSession();   }   /**	* startSession - Performs all the actions necessary to 	* initialize this session object. Tries to determine if the	* the user has logged in already, and sets the variables 	* accordingly. Also takes advantage of this page load to	* update the active visitors tables.	*/   function startSession(){	  global $database;  //The database connection	  session_start();   //Tell PHP to start the session	  /* Determine if user is logged in */	  $this->logged_in = $this->checkLogin();	  /**	   * Set guest value to users not logged in, and update	   * active guests table accordingly.	   */	  if(!$this->logged_in){		 $this->username = $_SESSION['username'] = GUEST_NAME;		 $this->userlevel = GUEST_LEVEL;		 $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);	  }	  /* Update users last active timestamp */	  else{		 $database->addActiveUser($this->username, $this->time);	  }	  	  /* Remove inactive visitors from database */	  $database->removeInactiveUsers();	  $database->removeInactiveGuests();	  	  /* Set referrer page */	  if(isset($_SESSION['url'])){		 $this->referrer = $_SESSION['url'];	  }else{		 $this->referrer = "/";	  }	  /* Set current url */	  $this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'];   }   /**	* checkLogin - Checks if the user has already previously	* logged in, and a session with the user has already been	* established. Also checks to see if user has been remembered.	* If so, the database is queried to make sure of the user's 	* authenticity. Returns true if the user has logged in.	*/   function checkLogin(){	  global $database;  //The database connection	  /* Check if user has been remembered */	  if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){		 $this->username = $_SESSION['username'] = $_COOKIE['cookname'];		 $this->userid   = $_SESSION['userid']   = $_COOKIE['cookid'];	  }	  /* Username and userid have been set and not guest */	  if(isset($_SESSION['username']) && isset($_SESSION['userid']) &&		 $_SESSION['username'] != GUEST_NAME){		 /* Confirm that username and userid are valid */		 if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){			/* Variables are incorrect, user not logged in */			unset($_SESSION['username']);			unset($_SESSION['userid']);			return false;		 }		 /* User is logged in, set class variables */		 $this->userinfo  = $database->getUserInfo($_SESSION['username']);		 $this->username  = $this->userinfo['username'];		 $this->userid	= $this->userinfo['userid'];		 $this->userlevel = $this->userinfo['userlevel'];		 return true;	  }	  /* User not logged in */	  else{		 return false;	  }   }   /**	* login - The user has submitted his username and password	* through the login form, this function checks the authenticity	* of that information in the database and creates the session.	* Effectively logging in the user if all goes well.	*/   function login($subuser, $subpass, $subremember){	  global $database, $form;  //The database and form object	  /* Username error checking */	  $field = "user";  //Use field name for username	  if(!$subuser || strlen($subuser = trim($subuser)) == 0){		 $form->setError($field, "* Username not entered");	  }	  else{		 /* Check if username is not alphanumeric */		 if(!eregi("^([0-9a-z])*$", $subuser)){			$form->setError($field, "* Username not alphanumeric");		 }	  }	  /* Password error checking */	  $field = "pass";  //Use field name for password	  if(!$subpass){		 $form->setError($field, "* Password not entered");	  }	  	  /* Return if form errors exist */	  if($form->num_errors > 0){		 return false;	  }	  /* Checks that username is in database and password is correct */	  $subuser = stripslashes($subuser);	  $result = $database->confirmUserPass($subuser, md5($subpass));	  /* Check error codes */	  if($result == 1){		 $field = "user";		 $form->setError($field, "* Username not found");	  }	  else if($result == 2){		 $field = "pass";		 $form->setError($field, "* Invalid password");	  }	  	  /* Return if form errors exist */	  if($form->num_errors > 0){		 return false;	  }	  /* Username and password correct, register session variables */	  $this->userinfo  = $database->getUserInfo($subuser);	  $this->username  = $_SESSION['username'] = $this->userinfo['username'];	  $this->userid	= $_SESSION['userid']   = $this->generateRandID();	  $this->userlevel = $this->userinfo['userlevel'];	  	  /* Insert userid into database and update active users table */	  $database->updateUserField($this->username, "userid", $this->userid);	  $database->addActiveUser($this->username, $this->time);	  $database->removeActiveGuest($_SERVER['REMOTE_ADDR']);	  /**	   * This is the cool part: the user has requested that we remember that	   * he's logged in, so we set two cookies. One to hold his username,	   * and one to hold his random value userid. It expires by the time	   * specified in constants.php. Now, next time he comes to our site, we will	   * log him in automatically, but only if he didn't log out before he left.	   */	  if($subremember){		 setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);		 setcookie("cookid",   $this->userid,   time()+COOKIE_EXPIRE, COOKIE_PATH);	  }	  /* Login completed successfully */	  return true;   }   /**	* logout - Gets called when the user wants to be logged out of the	* website. It deletes any cookies that were stored on the users	* computer as a result of him wanting to be remembered, and also	* unsets session variables and demotes his user level to guest.	*/   function logout(){	  global $database;  //The database connection	  /**	   * Delete cookies - the time must be in the past,	   * so just negate what you added when creating the	   * cookie.	   */	  if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){		 setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);		 setcookie("cookid",   "", time()-COOKIE_EXPIRE, COOKIE_PATH);	  }	  /* Unset PHP session variables */	  unset($_SESSION['username']);	  unset($_SESSION['userid']);	  /* Reflect fact that user has logged out */	  $this->logged_in = false;	  	  /**	   * Remove from active users table and add to	   * active guests tables.	   */	  $database->removeActiveUser($this->username);	  $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);	  	  /* Set user level to guest */	  $this->username  = GUEST_NAME;	  $this->userlevel = GUEST_LEVEL;   }   /**	* register - Gets called when the user has just submitted the	* registration form. Determines if there were any errors with	* the entry fields, if so, it records the errors and returns	* 1. If no errors were found, it registers the new user and	* returns 0. Returns 2 if registration failed.	*/   function register($subuser, $subpass, $subemail){	  global $database, $form, $mailer;  //The database, form and mailer object	  	  /* Username error checking */	  $field = "user";  //Use field name for username	  if(!$subuser || strlen($subuser = trim($subuser)) == 0){		 $form->setError($field, "* Username not entered");	  }	  else{		 /* Spruce up username, check length */		 $subuser = stripslashes($subuser);		 if(strlen($subuser) < 5){			$form->setError($field, "* Username below 5 characters");		 }		 else if(strlen($subuser) > 30){			$form->setError($field, "* Username above 30 characters");		 }		 /* Check if username is not alphanumeric */		 else if(!eregi("^([0-9a-z])+$", $subuser)){			$form->setError($field, "* Username not alphanumeric");		 }		 /* Check if username is reserved */		 else if(strcasecmp($subuser, GUEST_NAME) == 0){			$form->setError($field, "* Username reserved word");		 }		 /* Check if username is already in use */		 else if($database->usernameTaken($subuser)){			$form->setError($field, "* Username already in use");		 }		 /* Check if username is banned */		 else if($database->usernameBanned($subuser)){			$form->setError($field, "* Username banned");		 }	  }	  /* Password error checking */	  $field = "pass";  //Use field name for password	  if(!$subpass){		 $form->setError($field, "* Password not entered");	  }	  else{		 /* Spruce up password and check length*/		 $subpass = stripslashes($subpass);		 if(strlen($subpass) < 4){			$form->setError($field, "* Password too short");		 }		 /* Check if password is not alphanumeric */		 else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass)))){			$form->setError($field, "* Password not alphanumeric");		 }		 /**		  * Note: I trimmed the password only after I checked the length		  * because if you fill the password field up with spaces		  * it looks like a lot more characters than 4, so it looks		  * kind of stupid to report "password too short".		  */	  }	  	  /* Email error checking */	  $field = "email";  //Use field name for email	  if(!$subemail || strlen($subemail = trim($subemail)) == 0){		 $form->setError($field, "* Email not entered");	  }	  else{		 /* Check if valid email address */		 $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"				 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"				 ."\.([a-z]{2,}){1}$";		 if(!eregi($regex,$subemail)){			$form->setError($field, "* Email invalid");		 }		 $subemail = stripslashes($subemail);	  }	  /* Errors exist, have user correct them */	  if($form->num_errors > 0){		 return 1;  //Errors with form	  }	  /* No errors, add the new account to the */	  else{		 if($database->addNewUser($subuser, md5($subpass), $subemail)){			if(EMAIL_WELCOME){			   $mailer->sendWelcome($subuser,$subemail,$subpass);			}			return 0;  //New user added succesfully		 }else{			return 2;  //Registration attempt failed		 }	  }   }      /**	* editAccount - Attempts to edit the user's account information	* including the password, which it first makes sure is correct	* if entered, if so and the new password is in the right	* format, the change is made. All other fields are changed	* automatically.	*/   function editAccount($subcurpass, $subnewpass, $subemail){	  global $database, $form;  //The database and form object	  /* New password entered */	  if($subnewpass){		 /* Current Password error checking */		 $field = "curpass";  //Use field name for current password		 if(!$subcurpass){			$form->setError($field, "* Current Password not entered");		 }		 else{			/* Check if password too short or is not alphanumeric */			$subcurpass = stripslashes($subcurpass);			if(strlen($subcurpass) < 4 ||			   !eregi("^([0-9a-z])+$", ($subcurpass = trim($subcurpass)))){			   $form->setError($field, "* Current Password incorrect");			}			/* Password entered is incorrect */			if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){			   $form->setError($field, "* Current Password incorrect");			}		 }		 		 /* New Password error checking */		 $field = "newpass";  //Use field name for new password		 /* Spruce up password and check length*/		 $subpass = stripslashes($subnewpass);		 if(strlen($subnewpass) < 4){			$form->setError($field, "* New Password too short");		 }		 /* Check if password is not alphanumeric */		 else if(!eregi("^([0-9a-z])+$", ($subnewpass = trim($subnewpass)))){			$form->setError($field, "* New Password not alphanumeric");		 }	  }	  /* Change password attempted */	  else if($subcurpass){		 /* New Password error reporting */		 $field = "newpass";  //Use field name for new password		 $form->setError($field, "* New Password not entered");	  }	  	  /* Email error checking */	  $field = "email";  //Use field name for email	  if($subemail && strlen($subemail = trim($subemail)) > 0){		 /* Check if valid email address */		 $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"				 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"				 ."\.([a-z]{2,}){1}$";		 if(!eregi($regex,$subemail)){			$form->setError($field, "* Email invalid");		 }		 $subemail = stripslashes($subemail);	  }	  	  /* Errors exist, have user correct them */	  if($form->num_errors > 0){		 return false;  //Errors with form	  }	  	  /* Update password since there were no errors */	  if($subcurpass && $subnewpass){		 $database->updateUserField($this->username,"password",md5($subnewpass));	  }	  	  /* Change Email */	  if($subemail){		 $database->updateUserField($this->username,"email",$subemail);	  }	  	  /* Success! */	  return true;   }      /**	* isAdmin - Returns true if currently logged in user is	* an administrator, false otherwise.	*/   function isAdmin(){	  return ($this->userlevel == ADMIN_LEVEL ||			  $this->username  == ADMIN_NAME);   }      /**	* generateRandID - Generates a string made up of randomized	* letters (lower and upper case) and digits and returns	* the md5 hash of it to be used as a userid.	*/   function generateRandID(){	  return md5($this->generateRandStr(16));   }      /**	* generateRandStr - Generates a string made up of randomized	* letters (lower and upper case) and digits, the length	* is a specified parameter.	*/   function generateRandStr($length){	  $randstr = "";	  for($i=0; $i<$length; $i++){		 $randnum = mt_rand(0,61);		 if($randnum < 10){			$randstr .= chr($randnum+48);		 }else if($randnum < 36){			$randstr .= chr($randnum+55);		 }else{			$randstr .= chr($randnum+61);		 }	  }	  return $randstr;   }};/** * Initialize session object - This must be initialized before * the form object because the form uses session variables, * which cannot be accessed unless the session has started. */$session = new Session;/* Initialize form object */$form = new Form;?>

View Active

<?if(!defined('TBL_ACTIVE_USERS')) {  die("Error processing page");}$q = "SELECT username FROM ".TBL_ACTIVE_USERS	." ORDER BY timestamp DESC,username";$result = $database->query($q);/* Error occurred, return given name by default */$num_rows = mysql_numrows($result);if(!$result || ($num_rows < 0)){   echo "Error displaying info";}else if($num_rows > 0){   /* Display active users, with link to their info */   echo "<table align=\"left\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n";   echo "<tr><td><font size=\"2\">\n";   for($i=0; $i<$num_rows; $i++){	  $uname = mysql_result($result,$i,"username");	  echo "<a href=\"userinfo.php?user=$uname\">$uname</a> / ";   }   echo "</font></td></tr></table><br>\n";}?>

@ That is all of the code ^^ thank you for support... ColdEdge

Link to comment
Share on other sites

PHP Download Limitation Scritp@ Here is the code for this script all i need is for it to set each downloaded file (.zip or .rar) as 1 Credit and if member downloads his credits go down until he/she hit "0".... if this happends they will be redirected to a page which will say..."Sorry, <?php $GET['username']; ?>! But your Credits have reached "0". Please wait <?php $GET['time_refreshe']; ?> until you can download again."But for this download script I need it to use session and to hide file exnetsion some somethng like this....if {$session->0}; echo "You Must Be logged in to Download, Please Login First!";else { @ download script will allow downloads....and exnesion...so i set the download link like this /bamboo-blade/bamboo_blade_001.zip <-- an example.... of how link looks i need it to look like this..../bamboo-blade/?dl=12345 <--- 12345 like a # which will hide the file name...and here is the script....

<?php// change this value below$cs_conn = mysql_connect('localhost', 'animefro_admin', 'Master2992@anime!');mysql_select_db('animefro_website', $cs_conn);mysql_query("CREATE TABLE IF NOT EXISTS `downloaded` (  `filepath` varchar(255) NOT NULL,  `ipadres` varchar(15) NOT NULL,  `last_access` datetime NOT NULL,  UNIQUE KEY `filepath` (`filepath`,`ipadres`),  KEY `ipadres` (`ipadres`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");$path = addslashes($_SERVER['REQUEST_URI']);$ip = addslashes($_SERVER['REMOTE_ADDR']);$dl = false;$sql = sprintf("SELECT UNIX_TIMESTAMP(last_access) last_time FROM downloaded WHERE filepath = '%s' AND ipadres = '%s' ORDER BY last_access DESC", $path, $ip);$res = mysql_query($sql);if (mysql_num_rows($res) > 0) {	$last_xs = mysql_result($res, 0, 'last_time')+3600;	if ($last_xs < time()) {		mysql_query(sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip));		$dl = true;	} } else {	$sql = sprintf("REPLACE downloaded SET filepath = '%s', ipadres = '%s', last_access = NOW()", $path, $ip);	mysql_query($sql);	$dl = true;}if ($dl) {	$fullPath = $_SERVER['DOCUMENT_ROOT'].$path; 	if ($fd = fopen ($fullPath, "r")) {		$fname = basename($fullPath);		header('Content-type: application/octet-stream');		header('Content-Disposition: filename="'.$fname.'"');		header('Content-length: '.filesize($fullPath));		header('Cache-control: private'); 		while(!feof($fd)) {			$buffer = fread($fd, 2048);			echo $buffer;		}		fclose ($fd);		exit;	}} else {	header('Location: limit?act=error');}?>

it also uses .htaccess so here is the code for that.....htaccess

RewriteEngine onRewriteRule (.*)(pdf|zip|rar|)$ dl.php [QSA]

Thank You for support!

Link to comment
Share on other sites

Good lord.Was The Grandmaster of C++ not available?I don't think you're going to find a lot of people willing to change that amount of code for you, not for free anyway. If you want to do it yourself, we'll be happy to help show you how.

Link to comment
Share on other sites

Yes, i am willing to do it my self but i need people to guide me and to tell me is it write or wrong and should i add or remove lines of PHP code ^^ I will start with the registration page piece by piece i will be doing every code here... I am not asking for the entire code modification i am just asking for anything that you can help with like how to add e-mail field to password recovery page or how to set the credit system ^^....That about it... if i did have any spare cash i would be much more happyier to pay some one to do it for me but all i have is $29.00 bucks not that much....

Link to comment
Share on other sites

ok so for database table as defult tables are:

CREATE TABLE users (username varchar(30) primary key,password varchar(32),userid varchar(32),userlevel tinyint(1) unsigned not null,email varchar(50),timestamp int(11) unsigned not null);
so to add more fields to it i should add the following to database....
CREATE TABLE users (username varchar(30) primary key,password varchar(32),first_name varchar(50), <-- not shure } I think both first and last names can follow layout of usernamelast_name varchar(50), <-- not shure }location varchar(150), <-- i think this is correct } I seen this some where so it should be correctage int(2) unsigned not null, <-- extreamly not shure } Never got how this worksip varchar(15) not null unique key, <-- i think this is correct } this should add IP record to MySQL databaselast_active datetime not null. <-- not shure } i think this should add last active in time but not shure....userid varchar(32),userlevel tinyint(1) unsigned not null,email varchar(50),timestamp int(11) unsigned not null);
Link to comment
Share on other sites

The first name and last name are fine as varchar, location probably also. For the age, an unsigned tinyint will work. Unsigned tinyint goes from 0 to 255 (1 byte), so that's probably enough for age. A signed tinyint goes from -127 to 128, but you don't need age to be negative so might as well make it unsigned. The IP is fine at 15 characters ('XXX.XXX.XXX.XXX'), but I'm not sure if you want to make that unique. If 2 people try to register or sign in from the same computer it will cause a database error. For timestamps in a database, instead of a native date format I always prefer to use an integer instead, and use Unix timestamps. You can get the current Unix timestamp in PHP using the time() function, and it's easy to compare dates when they're just numbers.More info on data types in MySQL here:http://dev.mysql.com/doc/refman/5.0/en/data-types.html

Link to comment
Share on other sites

Part 2 Registration Script...

<?/** * The user is already logged in, not allowed to register. */if($session->logged_in){   echo "<h1>Registered</h1>";   echo "<p>We're sorry <b>$session->username</b>, but you've already registered. "	   ."<a href=\"main.php\">Main</a>.</p>";}/** * The user has submitted the registration form and the * results have been processed. */else if(isset($_SESSION['regsuccess'])){   /* Registration was successful */   if($_SESSION['regsuccess']){	  echo "<h1>Registered!</h1>";	  echo "<p>Thank you <b>".$_SESSION['reguname']."</b>, your information has been added to the database, "		  ."you may now <a href=\"main.php\">log in</a>.</p>";   }   /* Registration failed */   else{	  echo "<h1>Registration Failed</h1>";	  echo "<p>We're sorry, but an error has occurred and your registration for the username <b>".$_SESSION['reguname']."</b>, "		  ."could not be completed.<br>Please try again at a later time.</p>";   }   unset($_SESSION['regsuccess']);   unset($_SESSION['reguname']);}/** * The user has not filled out the registration form yet. * Below is the page with the sign-up form, the names * of the input fields are important and should not * be changed. */else{?><h1>Register</h1><?if($form->num_errors > 0){   echo "<td><font size=\"2\" color=\"#ff0000\">".$form->num_errors." error(s) found</font></td>";}?><form action="process.php" method="POST"><table align="left" border="0" cellspacing="0" cellpadding="3"><tr><td>Username:</td><td><input type="text" name="user" maxlength="30" value="<? echo $form->value("user"); ?>"></td><td><? echo $form->error("user"); ?></td></tr><tr><td>Password:</td><td><input type="password" name="pass" maxlength="30" value="<? echo $form->value("pass"); ?>"></td><td><? echo $form->error("pass"); ?></td></tr><tr><td>First Name:</td><td><input type="text" name="first_name" maxlength="50" value="<? echo $form->value("first_name"); ?>"></td><td><? echo $form->error("first_name"); ?></td></tr><tr><td>Last Name:</td><td><input type="text" name="last_name" maxlength="50" value="<? echo $form->value("last_name"); ?>"></td><td><? echo $form->error("last_name"); ?></td></tr><tr><td>Location:</td><td><input type="text" name="location" maxlength="150" value="<? echo $form->value("location"); ?>"></td><td><? echo $form->error("location"); ?></td></tr><tr><td>Age:</td><td><input type="text" name="age" maxlength="2" value="<? echo $form->value("age"); ?>"></td><td><? echo $form->error("age"); ?></td></tr><tr><td>Email:</td><td><input type="text" name="email" maxlength="50" value="<? echo $form->value("email"); ?>"></td><td><? echo $form->error("email"); ?></td></tr><tr><td colspan="2" align="right"><input type="hidden" name="subjoin" value="1"><input type="submit" value="Join!"></td></tr><tr><td colspan="2" align="left"><a href="main.php">Back to Main</a></td></tr></table></form><?}?>

now i am not sure should i make Age: input as text with max length of 2 and i am not sure where to add IP fetch line and Credit line to this form.....@ This script requires session.php which I will be puting up soon...

Link to comment
Share on other sites

I'm not sure what credit is for, but don't bother putting the IP in the form. When they submit the form and you're getting ready to put them in the database, you can get their IP from $_SERVER['REMOTE_ADDR']. If you want to put their IP in the form just to let them know that you're storing it, you can just use text.<tr><td>Your IP:</td><td><?php echo $_SERVER['REMOTE_ADDR']; ?></td><td></td></tr>Keep in mind that IPs change though, a given user won't always have the same IP, and a given IP won't always apply to the same user.

Link to comment
Share on other sites

@ JustsomeguyI have a question. Do you think I can make Credit System as a seperat MySQL table?

username varchar(50) Primary Key NOT NULL,ip varchar(15),credit_count varcahr(20),credit_refresh datetime(24),

I am not sure what should i do.. could you give me any advice how to make this credits download system work? This idea comes from a site called DGEMU but they make it so when you download a file say 5.67 MB it minuses that amount from your credits which are "20" and then refreshes them for every one after 12 hours..--EDITED--Ok, I will explain what the credits are for. Upon registration I wish to limit how much a member can download in a day do to this I am trying to build a credit/curency system simular to one found on DGEMU.COM a site which provides GBA, ATARI, DS Roms. My site has nothing to do with that as my site is aimed to build a free Anime/Manga community. Some of the Manga volumes can get as big as 105.45 MB and bigger. Do to this I need help making the download system more then anything else in this entire post. What will the download system do? It will set member "Download Credits" to 20 upon registration. Each time a member downloads a file "2" credits are subtracted from his/her account until they reach "0" when they reach "0" they will no longer be able to download all they will get is being send to credits.php?act=limit and this where they will see a message like this "We are sorry, USERNAME! But your account has reached "0" Download Credits. Your credits will be reset in TIME hours or min. Thank You!" So this is a basic thought behind this request to limit the download amount.

Link to comment
Share on other sites

I guess it depends how you want it to work. If you want credits to be refreshed 12 hours after the user uses them, then you store a timestamp in the database like you're doing and check the timestamp the next time they download to see if credits should be refreshed. If credits get refreshed for all users at a specific time (like 00:00 and 12:00 of each day), then you'll need to set up a cron job or scheduled task to do that.

Link to comment
Share on other sites

@ JustsomeguyThank you for supporting me all this way ^^But I think I will drop this insane ideas of having Credit System... my Shared Hosting provides unlimited bandwitch the problems is that I have to contact them every time it is reaching critical. But if I may ask could you help me with much simpler task then this? The task is: Download System Version 1Ok, for this system there are no credits. All this dose if some one downloaded say: bamboo_blade_vol1.zip or bamboo_blade_vol1.rar then they can not download that file for 5 min... So if they click download it will send them to limit.php?act=time where it will say "Your IP: XXX.XXX.XXX.XXX has just downloaded finished downloading a file please wait TIME <-- to make it active some how so it counts down from 5 min, and after that is done it send them to limit.php?act=time where a message like this will show up "You are able to download again." The thing with this if they download "1" file from any where so if they say download: bamboo_blade_vol1.zip and then try to download say: airgear_vol1.zip they will resive the "limit.php?act=time" so each time they download any file from and directory they have to wait "5 min" And other help i need is that i need to hash the download link so they dont see where the file is located.... so instead of say: bamboo_blade_vol1.zip or .rar they will see say: 564b45sfg4542bgsc342xv5.zip ?????Thank You.-ColdEdge

Link to comment
Share on other sites

If you want to limit how much people can download, add a field to the users table in the database where you can store a timestamp, so an integer field. You need a PHP page to handle downloading, so when they click a link to download a file they actually click a link to a PHP page that does all the checking. e.g. download.php?file=100. The script would check the last time they downloaded, etc, update the timestamp if they're allowed to download, and then give them the file. For security, you can configure the web server to disallow all access to the directory containing your files, and just have PHP read the data and send it to them. You can use file_get_contents to do that, with a few headers. This would force the download of a text file, for example:

<?php$fname = '/path/to/file.txt';header('Content-type: application/octet-stream');header('Content-disposition: attachment; filename="download.txt"');header('Content-length: ' . filesize($fname));echo file_get_contents($fname);?>

So they will download the file without ever being linked to it, they won't even know the original name. You can name the file anything you want in the content-disposition header.

Link to comment
Share on other sites

It needs to get the ID of the file, you can find that in $_GET. Everything sent through the URL is available in $_GET.http://www.php.net/manual/en/reserved.variables.get.phpOnce you have the ID of the file they want, you make a connection to your database the same way you would on any other page, and look up the file with that ID. The database should have the filename stored in it (you'll probably need to build a form where you upload files and it saves everything in the database). Once you have the filename, then you send the headers and output the data like the code above does.You can also look up the user record in the database and check when the last time was that they downloaded a file, and you'll also need to update that record to indicate that they're downloading a file now.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...