Jump to content

ianh

Members
  • Posts

    27
  • Joined

  • Last visited

    Never

Profile Information

  • Gender
    Not Telling

ianh's Achievements

Member

Member (2/5)

0

Reputation

  1. Ensure you initiate the session at the very top of each of your PHP pages: <?php session_start(); //rest of your code here... ?>
  2. @dzelenika and @Psycho thanks for your replies, really appreciate it To clarify, the category names will always be added as new by the admin (me), not by the end user. Only records in the 'data entry' table can be added/edited/removed by the end user. @Psycho, I see what you mean about deleting records is tricky. Maybe the records can be deleted on the fly directly from the database using AJAX? Or even saved into session variables for standard form post submit? What do you think?
  3. Hi everyone, I have the task of building a PHP page where users can enter or remove as many records as they like into different categories. This then makes the number of records entered unknown, and therefore it becomes more complicated. To make this clearer, I have attached an image of what I am trying to do. Two questions: - Before submitting the form, how can each record entry be matched with the correct category? (maybe hidden form fields somehow?) - What is the best way of inserting each record (and it's associated category) into a MySQL database table from a single form submit? I want to try and keep this as simple as possible as the data will later be updated, removed etc. I'm experiencing a brain fart and just cannot picture the best way of going about this Any help and advice is much appreciated! Thanks in advance. Basic table schema example... CATEGORY TABLE ---------------------------- | catid | category | ---------------------------- | 1 | Category A | | 2 | Category B | etc. etc. ---------------------------- DATA ENTRY TABLE ---------------------------- dataid | catid | data | -------------------------------- | 1 | 2 | data xyz | | 2 | 1 | data zyx | etc. etc etc. --------------------------------
  4. PFMaBiSmAd thank you so much! I couldn't get the .htaccess to work (seemed to generate internal server error). .htaccess file (not working) php_value session.save_path "/mypathgoeshere" php_value session.gc_maxlifetime 14400 php_value session.gc_probability 1 So I ended up putting the following code in each of my PHP pages containing session_start() which worked. PHP (working) session_save_path('/mypathgoeshere'); ini_set('session.gc_maxlifetime', 14400); ini_set('session.gc_probability', 1); session_start();
  5. It appears that my '/tmp' folder on my shared hosting (GoDaddy) account is full with session files and it seems I have to wait (up to 72hrs) for their hopeless admins to clear out the folder. The strange things is everything was working fine a couple of days ago. Now sometimes I get errors on my PHP page saying disk is full and session cache error. Sometimes don't even get these errors. I can't seem to get back these errors now. Is there anyway to generate session or disk errors in PHP? Also, the login page doesn't work. It just doesn't login and reloads itself each time. I think it might be due to either the '/tmp' folder being full or it's getting confused with session variables that haven't been destroyed. I'm really not sure? Any help or insight would be much appreciated. Class creating the session variables and verifying login: <?php session_start(); //global $loginTime; /** * LoginSystem * * Simple Login system with sessions and MySQL User DB * * @version 1.0 * @author A.Surrey (www.surneo.com) * * */ class LoginSystem { var $db_host, $db_name, $db_user, $db_password, $connection, //$userid, //added by IH 18-January-2011 $username, $password, $userip, $loginTime, $timeout; /** * Constructor */ function LoginSystem() { require_once('../../config/settings.php'); $this->db_host = $dbhost; $this->db_name = $dbname; $this->db_user = $dbuser; $this->db_password = $dbpassword; } /** * Check if the user is logged in * * @return true or false */ function isLoggedIn() { if($_SESSION['LoggedIn']) { return true; } else return false; } /** * Check username and password against DB * * @return true/false */ //function doLogin($username, $password) function doLogin($username, $password, $userip) { $timezone = 0; //(GMT -5:00) EST (U.S. & Canada) $loginTime = gmdate("Y-m-j H:i:s", time() + 3600*($timezone+date("I"))); $this->connect(); $this->username = $username; $this->password = $password; $this->userip = $userip; // check db for user and pass here. //$sql = sprintf("SELECT UserID, UserName, Password FROM Users WHERE UserName = '%s' and Password = '%s'", $sql = sprintf("SELECT UserID, UserName, FullName, Password FROM Users WHERE UserName = '%s' and Password = '%s' AND ActiveUser = '1'", $this->clean($this->username), md5($this->clean($this->password))); $result = mysql_query($sql, $this->connection); // If no user/password combo exists return false if(mysql_affected_rows($this->connection) != 1) { $this->disconnect(); return false; } else // matching login ok { $row = mysql_fetch_assoc($result); $userid = $row['UserID']; // more secure to regenerate a new id. session_regenerate_id(); //set session vars up $_SESSION['LoggedIn'] = true; $_SESSION['userName'] = $this->username; $_SESSION['userID'] = $row['UserID']; $_SESSION['fullName'] = $row['FullName']; //$this->getLoginTime(); //return $this->loginTime; //#### WORKING QUERY - MANUAL DATE VALUE #### //$sql2 = 'UPDATE Users SET LastLogin = "2011-01-18 23:55:32" WHERE UserID = "' . $userid.'"'; //#######################// //$sql2 = 'UPDATE Users SET LastLogin = "'.$loginTime.'" WHERE UserID = "'.$userid.'"'; $sql2 = 'UPDATE Users SET LastLogin = "'.$loginTime.'", UserIP = INET_ATON("'.$this->userip.'") WHERE UserID = "'.$userid.'"'; $result2 = mysql_query($sql2, $this->connection); //echo '<script>alert("'.$sql2.'");</script>'; } $this->disconnect(); return true; } function sessionTimer() { //unset($_SESSION['timeout']); session_start(); $this->inactivesession = $inactivesession; // set timeout period in seconds (14400 = 4 hours) $this->inactivesession = 1400; $this->session_life = $session_life; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $this->session_life = time() - $_SESSION['timeout']; if($this->session_life > $this->inactivesession) { session_destroy(); //header("Location: logout.php?msg=2"); return true; } else { return false; } } //$_SESSION['timeout'] = time() + $this->session_life; $_SESSION['timeout'] = time() + $this->inactivesession; //$_SESSION['timeout'] = time(); //return false; } /** * Destroy session data/Logout. */ function logout() { unset($_SESSION['LoggedIn']); unset($_SESSION['fullName']); unset($_SESSION['userName']); unset($_SESSION['userID']); unset($_SESSION['timeout']); session_destroy(); } /** * Connect to the Database * * @return true/false */ function connect() { $this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_password) or die("Unable to connect to MySQL"); mysql_select_db($this->db_name, $this->connection) or die("Unable to select DB!"); // Valid connection object? everything ok? if($this->connection) { return true; } else return false; } /** * Disconnect from the db */ function disconnect() { mysql_close($this->connection); } /** * Cleans a string for input into a MySQL Database. * Gets rid of unwanted characters/SQL injection etc. * * @return string */ function clean($str) { // Only remove slashes if it's already been slashed by PHP if(get_magic_quotes_gpc()) { $str = stripslashes($str); } // Let MySQL remove nasty characters. $str = mysql_real_escape_string($str); return $str; } /** * create a random password * * @param int $length - length of the returned password * @return string - password * */ function randomPassword($length = { $pass = ""; // possible password chars. $chars = array("a","A","b","B","c","C","d","D","e","E","f","F","g","G","h","H","i","I","j","J", "k","K","l","L","m","M","n","N","o","O","p","P","q","Q","r","R","s","S","t","T", "u","U","v","V","w","W","x","X","y","Y","z","Z","1","2","3","4","5","6","7","8","9"); for($i=0 ; $i < $length ; $i++) { $pass .= $chars[mt_rand(0, count($chars) -1)]; } return $pass; } } ?> Login page: <?php session_start(); require ('class/MathGuard.class.php'); require_once('class/LoginSystem.class.php'); $userip = $_SERVER['REMOTE_ADDR']; if(isset($_POST['Submit'])) { if((!$_POST['Username']) || (!$_POST['Password'])) { // display error message header('location: login.php?msg=1');// show error exit; } // ######## MatchGuard check ######## if (!MathGuard :: checkResult($_REQUEST['mathguard_answer'], $_REQUEST['mathguard_code'])) { //show_error ("Incorrect Security Code entered"); header('location: login.php?msg=3'); exit; } $loginSystem = new LoginSystem(); if($loginSystem->doLogin($_POST['Username'],$_POST['Password'],$userip)) { /** * Redirect here to your secure page */ header('location: view_articles.php'); } else { header('location: login.php?msg=2'); exit; } } /** * show Error messages * */ function showMessage() { if(is_numeric($_GET['msg'])) { switch($_GET['msg']) { //case 1: echo "Please fill both fields."; case 1: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Please fill in all fields!</p></div>'; break; //case 2: echo "Incorrect Username or Password!"; case 2: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Incorrect Username or Password!</p></div>'; break; //case 3: echo "Incorrect Security Code"; case 3: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Incorrect Security answer!</p></div>'; break; } } } /* function show_error($myError) { echo $myError; //stop executing script and display the form exit(); }*/ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login</title> <meta name="robots" content="noindex, nofollow" /> <link rel="stylesheet" type="text/css" href="css/login.css" /> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/supersleight.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".block").fadeIn(1000); $(".msg").fadeIn(1000); $('.msg').supersleight(); }); </script> </head> <body> <div id="wrap"> <?php showMessage();?> <div class="block"> <div class="head"> <h3>Login</h3><!--<a href="#">Forgot Password?</a>--> </div> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div class="body"> <div class="div-row"> <label for="username">Username</label><input type="text" id="Username" name="Username" maxlength="30" /> </div> <div class="div-row"> <label for="password">Password</label><input type="Password" id="Password" name="Password" maxlength="30" /> </div> <div class="div-row"> <?php MathGuard::insertQuestion(); ?> </div> <div class="send-row"> <button id="login" value="Login" type="submit" name="Submit"></button> </div> </div> </form> </div> </div> </body> </html> Make pages secure include: <?php session_cache_expire(240); session_start(); require('./class/LoginSystem.class.php'); $loginSys = new LoginSystem(); /** * if not logged in goto login form, otherwise we can view our page */ if(!$loginSys->isLoggedIn()) { header("Location: ./login.php"); exit; } $sessionTime = new LoginSystem(); if($sessionTime->sessionTimer()) { header("Location: ./logout.php?msg=2"); exit; } ?> Logout page: <?php session_start(); require('class/LoginSystem.class.php'); $loginSys = new LoginSystem(); $loginSys->logout(); function showMessage() { if(is_numeric($_GET['msg'])) { switch($_GET['msg']) { case 1: echo '<div class="msg" style="border:1px; border-color:#8be57e; background:#b4efab; color:#337129;"><img src="images/icons/succes.png" alt=""/><p>You have logged out successfully.</p></div>'; break; case 2: echo '<div class="msg"><img src="images/icons/error.png" alt=""/><p>Due to inactivity your session has expired.</div>'; break; } } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login</title> <meta name="robots" content="noindex, nofollow" /> <link rel="stylesheet" type="text/css" href="css/login.css" /> <link rel="stylesheet" type="text/css" href="css/ui.dialog.css" /> <style type="text/css"> body{ background-image: none; } </style> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/supersleight.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".block").fadeIn(1000); $(".msg").fadeIn(1000); $('.msg').supersleight(); }); </script> </head> <body> <div id="wrap"> <?php showMessage();?> <div class="block"> <div class="head"> <h3>Logged Out</h3> </div> <div class="body"> <p align="center"><font color="#000000"><b>Redirecting to the 'Login' page in <span id="seconds" style="color:#ff0000;">10</span> seconds.</b></font></p> <script language="JavaScript"> var seconds = 10; setInterval( function(){ if (seconds <= 1) { window.location = 'http://domain.tld/cms/login.php'; } else { document.getElementById('seconds').innerHTML = --seconds; } }, 1000 ); </script> <br><br> <p align="center">If you are not redirected, go straight to the <a href="login.php"><font size="3" color="blue"><b>Login</b></font></a> page.</p> </div> </div> </div> </body> </html> MathGuard class (works fine and I have not changed anything in this file) <? class MathGuard { /** A main hashing function: concat of user's answer, hour and the additional prime number (default 37) */ function encode($input, $prime) { return md5($input.date("H").$prime); } /** This function generates the hash code from the two numbers * @param $a first number * @param $b second sumber * @param $prime additional number to encode with * */ function generateCode($a, $b, $prime) { $code = MathGuard::encode($a + $b, $prime); return $code; } /** This function checks whether the answer and generated security code match * @param $mathguard_answer answer the user has entered * @param $mathguard_code hashcode the mathguard has generated */ function checkResult($mathguard_answer, $mathguard_code, $prime = 37) { // echo("prime; $prime, $mathguard_answer"); $result_encoded = MathGuard::encode($mathguard_answer, $prime); if ($result_encoded == $mathguard_code) return true; else return false; } /** this function inserts the two math term into your form, the parameter is optional */ function insertQuestion($prime = 37) { //default prime is 37, you can change it when specifying the different parameter $a = rand() % 10; // generates the random number $b = rand() % 10; // generates the random number $code = MathGuard :: generateCode($a, $b, $prime); echo ("<label for=mathcheck>Security: $a + $b =</label> <input type='input' name='mathguard_answer' size='2' maxlength='4' /><input type='hidden' name='mathguard_code' value='$code' />"); } /** this function returns math expression into your form, the parameter is optional * quite simmilar to insertQuestion, but returns the output as a text instead of echoing */ function returnQuestion($prime = 37) { //default prime is 37, you can change it when specifying the different parameter $a = rand() % 10; // generates the random number $b = rand() % 10; // generates the random number $code = MathGuard :: generateCode($a, $b, $prime); return ("<label for=mathcheck>Security: $a + $b =</label> <input type='input' name='mathguard_answer' size='2' maxlength='4' /><input type='hidden' name='mathguard_code' value='$code' />"); } } ?> edit: removed domain name
  6. Many thanks mate. Can't believe I missed out the bracket
  7. Hi, I am trying to perform a union join query but it is producing an error and really not sure why. I think it has something to do with status being -1 but not sure. Should negative values be treated differently? SELECT title, abstract, body, status, right_column FROM Articles WHERE category_id = 2 AND id = 3062 AND status = -1) UNION (SELECT title, abstract, body, status, right_column FROM Articles WHERE category_id = 2 AND id > 3062 AND status = '-1' AND right_column = "1" ORDER BY id ASC LIMIT 1) ORDER BY right_column ASC gives error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') UNION (SELECT title, abstract, body, status, right_column FROM Articles WHERE ' at line 1 Any help is much appreciated. Thanks in advance.
  8. Works perfectly! Thanks mate Strange about the inverted commas. Perhaps it is something to do with whe there are a number of ANDs in a UNION statement? Corrected/working code: (SELECT id, title, abstract, body, status, right_column FROM Articles WHERE category_id = 2 AND id = 3015 AND status = 1) UNION (SELECT id, title, abstract, body, status, right_column FROM Articles WHERE category_id = 2 AND id > 3015 AND status = 1 AND right_column = "1" ORDER BY id ASC LIMIT 1) ORDER BY right_column ASC
  9. ...and here are all the records from the same category..... [attachment deleted by admin]
  10. Here is the Articles table structure..... [attachment deleted by admin]
  11. I'm no expert, but to do a join you need to have common field(s). If your want to put the data in an email (I presume with PHP or other language) you can just output and process the queries individually.
  12. For some reason my UNION select query doesn't seem to return the next record. I have 3 records with the same 'category', 'status', yet the 'right_column' is different. id 3015 category_id 2 status 1 right_column 0 id 3021 category_id 2 status 1 right_column 1 id 3023 category_id 2 status 1 right_column 0 I want to select 2 records; the current record (3015) and the next highest record from 3015 which should be 3021, however it is returning 3023 ?? It's driving me insane. Ideas anyone? Thanks in advance. (SELECT id, title, abstract, body, status, right_column FROM Articles WHERE category_id = 2 AND id = 3015 AND status = 1) UNION (SELECT id, title, abstract, body, status, right_column FROM Articles WHERE category_id = 2 AND id > 3015 AND status = 1 AND right_column = 1 ORDER BY id ASC LIMIT 1) ORDER BY right_column ASC
  13. I think I solved it by having 1 UNION query, so I therefore now have 1 query instead of 2, eliminating the need for processing 2 recordsets. Code changed to: <?php require_once (dirname(__FILE__). '/../conf.php'); $connection = mysql_pconnect(DB_HOST,DB_USER,DB_PASSWORD); mysql_select_db(DB_DATABASE,$connection); //#### UNION query - get first article and the next highest article with lower order_num #### $result = mysql_query("(SELECT title, abstract, body FROM Articles WHERE category_id = ".$str_categoryid." AND id = ".$str_articleid.") UNION (SELECT title, abstract, body FROM Articles WHERE category_id = ".$str_categoryid." AND id > ".$str_articleid." ORDER BY order_num DESC LIMIT 1)", $connection); while ($fielddata = mysql_fetch_array($result)) { echo $fielddata['title']."\n\n"; echo "<p><strong>".$fielddata['abstract']."</strong></p> \n\n"; echo $fielddata['body']; } ?> This displays the 2 records in the same record set, and uses far less code. Hope this helps someone.
  14. Bascially I want the queries to display the results in the same recordset. The results are in effect 2 articles which I want to display side by side.
×
×
  • 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.