PHP - Moved: Php, Output For Logged In User?
This topic has been moved to Third Party PHP Scripts.
http://www.phpfreaks.com/forums/index.php?topic=357163.0 Similar TutorialsHello, i've got some shop script which has 2 payment modules which i'd like to use for something else, the payment modules only work if the user is logged in though, i tried to make them standalone scripts but that didn't work out too well. So now i decided to go another way and just let everyone have the same session so everyone will be using the same username&password automatically. the index file looks like this: Code: [Select] <?php include('./inc/config.php'); include('./inc/functions.php'); include('./lang/'.$language.'.lng'); $id = addslashes($_REQUEST["id"]); $user = addslashes($_REQUEST["username"]); $pass = addslashes($_REQUEST["password"]); $language = strtolower($language); if(empty($id)) $id =1; $file = mysql_query('SELECT * FROM navi_'.$language.' WHERE id="'.$id.'"'); if(mysql_num_rows($file)>0) $file = mysql_fetch_array($file); else $file = mysql_fetch_array(mysql_query('SELECT * FROM navi_'.$language.' WHERE id="404"')); if(!empty($user) AND !empty($pass)) {$query = mysql_query('SELECT * FROM users WHERE username="'.$user.'" AND pass="'.md6($pass).'"'); if(mysql_num_rows($query) == 1) {$_SESSION[$session_prefix."user"] = ucfirst($user); echo'<meta http-equiv="refresh" content="0; url=index.php?id=8">';} else $error = 'Username oder Passwort ist falsch.';} include('./designe/'.$designe.'/head.tpl'); include('./designe/'.$designe.'/navi.php'); include('./designe/'.$designe.'/middle.tpl'); if(file_exists('./pages/'.$file["file"])) {echo'<h1>'.ucfirst($file["title"]).'</h1>'; include('./pages/'.$file["file"]);} if(!empty($error)) echo '<font color="red">'.$error.'</font>'; include('./designe/'.$designe.'/foot.tpl'); ?> Now i tried alot of things including adding: Code: [Select] session_start(); $_SESSION["username"] = "peter"; $_SESSION["user"] = "peter"; $_SESSION["id"] = "1"; $_SESSION["pass"] = "peter"; $_SESSION["password"] = "peter"; or Code: [Select] $id = "1"; $user = "peter"; $username = "peter"; $pass = "peter"; $password = "peter"; also a combination of both, nothing works, but i don't understand why ? Any help is appreciated. /Edit, i tried adding it to the paymentmodule .php aswell, but no luck. Hello all, This has probably been asked before but I couldn't find through search. And I'm pretty sure is not possible, but... Is there a way of displaying the windows logged on user? or get the name of the compter? as I know I can get the ip address. The reason I ask. Each user has their own network account but on occasion we need to log on a user as a generic account we have. And I want to check if it's this user accessing the page so different options etc can be displayed. I could use the computer name to check this as we log all activity. I could then query the log using the comp name to find logged on user. Unfortunately the log does not hold ip, which would seem obvious but it doesn't Many Thanks Hi there,
I've been searching the internet for the best way to check if the user has been logged in. Some codes have security breaches. So I'm not sure where to start.
Here's what I've come up with:
The user logs in and is checked whether he/she is a valid user, if not return false and if true carry on and create session, I read the post that Jacques1 made about session feedback and implemented what he said. After that the session variables are assigned and then the user id, session_id and a unique identifier to check against on each page load are inserted into a database and then the user is logged in.
Here's my code: (please note this is in a class and only shows the login function)
function Login($username, $password) { try { $db = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8", DB_USERNAME, DB_PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch(PDOException $ex) { echo "Unable to connect to DB"; error_log($ex->getMessage()); } try { $User_Info = $db->prepare("SELECT * FROM users WHERE username=:username"); $User_Info->bindValue(":username", $username, PDO::PARAM_STR); $User_Info->execute(); $Info = $User_Info->fetchAll(PDO::FETCH_ASSOC); $salt = $Info['salt']; $password = $salt . $password; $password = $this->CreateHash($password); $unique_key = $this->GenerateRandom(); $unique_key = $this->CreateHash($unique_key); $Check_User = $db->prepare("SELECT * FROM users WHERE username=:username AND password=:password"); $Check_User->bindValue(":username", $username, PDO::PARAM_STR); $Check_User->bindValue(":password", $password, PDO::PARAM_STR); $Check_User->execute(); if($Check_User->rowCount() > 0) { while($row = $Check_User->fetchAll(PDO::FETCH_ASSOC)) { session_destroy(); session_start(); $_SESSION = array(); session_regenerate_id(true); $_SESSION['username'] = $row['username']; $session_id = session_id(); $user_id = $row['id']; $Check_Logged_In = $db->prepare("DELETE FROM logged_in_users WHERE user_id=:userid"); $Check_Logged_In->bindValue(":user_id", $user_id, PDO::PARAM_STR); $Check_Logged_In->execute(); $has_changed = $Check_Logged_In->rowCount(); if($has_changed > 0) { $Logged_In = $db->prepare("INSERT INTO logged_in_users (id, user_id, session_id, unique_key) VALUES (NULL, :user_id, :session_id, :unique_key)"); $Logged_In->bindValue(":user_id", $user_id, PDO::PARAM_STR); $Logged_In->bindValue(":session_id", $session_id, PDO::PARAM_STR); $Logged_In->bindValue(":unique_key", $unique_key, PDO::PARAM_STR); $Logged_In->execute(); $affected_rows = $Logged_In->rowCount(); if($affected_rows > 0) { return true; } } return false; } } return false; } catch(PDOException $ex) { echo "Unable to complete query"; error_log($ex->getMessage()); } }Thanks In the site I am making, the client wants one account for everyone (don't ask me why, it's a long, silly reason) And I'm wondering how I would configure mySQL to deal with that (I asked this in the mySQL area) and in PHP (For you guys ) what would I need to put in order for this to work. I'm very new with PHP and mySQL, so please forgive the nooby question. *EDIT* the admins have their own username and psw for adding, deleting, and editing articles. and that works. But all users that register will have this set user and psw displayed to them. I want to make it so they have to log in to see an article. Hi, I want have this code (below), how would I check if a user is logged in? I want to make it so they can only see 500 chars, or the full thing if they're logged in. Thanks! Code: [Select] public function __construct( $data=array() ) { if ( isset( $data['id'] ) ) $this->id = (int) $data['id']; if ( isset( $data['publicationDate'] ) ) $this->publicationDate = (int) $data['publicationDate']; if ( isset( $data['title'] ) ) $this->title = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['title'] ); if ( isset( $data['summary'] ) ) $this->summary = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['summary'] ); if ( isset( $data['content'] ) ) $this->content = $data['content']; if ( isset( $data['tags'] ) ) $this->tags = $data['tags']; } Hi, I'm trying to display a user review system allowing user's to vote. This works fine, but I'm trying to user php to only display the rating system if the user is logged in and display alternate text if they are not. I am getting the following error: Parse error: syntax error, unexpected T_ELSE in XXXXXX on line 182 Here's the code: Code: [Select] <?php if ($_SESSION['username']){ $query = mysql_query("SELECT * FROM locations WHERE name = '$location'"); while($row = mysql_fetch_array($query)) { $rating = (int)$row[rating] ?> <div class="floatleft"> <div id="rating_<?php echo $row[id]; ?>"> <span class="star_1"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 0) { echo"class='hover'"; } ?> /></span> <span class="star_2"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 1.5) { echo"class='hover'"; } ?> /></span> <span class="star_3"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 2.5) { echo"class='hover'"; } ?> /></span> <span class="star_4"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 3.5) { echo"class='hover'"; } ?> /></span> <span class="star_5"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 4.5) { echo"class='hover'"; } ?> /></span> </div> </div> <div class="star_rating"> (Rated <strong><?php echo $rating; ?></strong> Stars) </div> <div class="clearleft"> </div> } } <?php else { echo "Log in to review"; } ?> Thanks in advance for any help. I'm sure it's something trivial but I can't see it! How do I get the current logged in username or id using the Twitter API? i need to display the fullname and email of the logged in user. <?php session_start(); mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("db_register") or die(mysql_error()); $query = "SELECT` fullname`, `email` FROM `members` WHERE `username`='".$_SESSION['user']."' LIMIT 1"; if($doQuery = mysql_query($query)) { if(mysql_num_rows($doQuery)) { $user = mysql_fetch_assoc($doQuery); print_r($user); } else { echo 'No result returned for the query: '.$query; } } else { echo 'The following query failed: '.$query; } $id = $user['id']; $fullname = $user['fullname']; $email = $user['email']; } ?> <br> Fullname : <?php echo $fullname; ?> <br> Email : <? echo $email; ?> ?> HELP please . $sql = "SELECT id,username, date1, date2, total FROM datetable WHERE username = '".$_SESSION['uid']['username'] ."'"; Hello again, I ran into problem when trying to pull information for logged in user. I'm trying to display results for current user only who is signed in. Now I do have session_start(); and my query works if I replace '".$_SESSION['uid']['username'] ."'"; with 'specificusername' but when I run my current query displayed above it returns me all records with username = empty (I have some empty usernames for testing reasons). So that tells me that query cant find unique user name that is logged in. I don't get any errors and query still goes through. My datetable structure is
My uid is defined in another document like so and uses another table called "users" session_start(); $_SESSION['id'] = $row['idUsers']; $_SESSION['uid'] = $row['uidUsers']; $_SESSION['email'] = $row['emailUsers']; header("Location: ../member.php?login=success"); exit(); This query works on another page where it displays logged in username in html document. <?php echo $_SESSION['uid']; ?>
I have tried many different ways yesterday to modify my request ( WHERE username = $_SESSION['uid']; WHERE username = '".$_SESSION["uid"]) many other variations, but no matter what never returns logged in user information only empty username records. Can anyone see a problem with that query? or is it due to something else I'm missing?
Sorry, maybe this goes in MySQL thread not here in PHP page. If someone can, please move it. Thanks. Edited April 25, 2020 by sfia comment on where to post this topic Hello, I'm trying to build a registration/login system. I managed to set it up but i need that for the user when he/she is logged in to display his own information and to manage to edit them, First i need to display them, because i seem to not be doing it.. i know it's easy in principal but i am really new at this... So here is my code: The login.php page Code: [Select] <?php include ('database_connection.php'); if (isset($_POST['formsubmitted'])) { // Initialize a session: session_start(); $error = array();//this aaray will store all error messages if (empty($_POST['e-mail'])) {//if the email supplied is empty $error[] = 'You forgot to enter your Email '; } else { if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) { $Email = $_POST['e-mail']; } else { $error[] = 'Your EMail Address is invalid '; } } if (empty($_POST['Password'])) { $error[] = 'Please Enter Your Password '; } else { $Password = $_POST['Password']; } if (empty($error))//if the array is empty , it means no error found { $query_check_credentials = "SELECT * FROM members WHERE (Email='$Email' AND password='$Password') AND Activation IS NULL"; $result_check_credentials = mysqli_query($dbc, $query_check_credentials); if(!$result_check_credentials){//If the QUery Failed echo 'Query Failed '; } if (@mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull { // A match was made. $_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);//Assign the result of this query to SESSION Global Variable header("Location: page.php"); }else { $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect'; } } else { echo '<div class="errormsgbox"> <ol>'; foreach ($error as $key => $values) { echo ' <li>'.$values.'</li>'; } echo '</ol></div>'; } if(isset($msg_error)){ echo '<div class="warning">'.$msg_error.' </div>'; } /// var_dump($error); mysqli_close($dbc); } // End of the main Submit conditional. ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login Form</title> <style type="text/css"> body { font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; font-size:12px; } .registration_form { margin:0 auto; width:500px; padding:14px; } label { width: 10em; float: left; margin-right: 0.5em; display: block } .submit { float:right; } fieldset { background:#EBF4FB none repeat scroll 0 0; border:2px solid #B7DDF2; width: 500px; } legend { color: #fff; background: #80D3E2; border: 1px solid #781351; padding: 2px 6px } .elements { padding:10px; } p { border-bottom:1px solid #B7DDF2; color:#666666; font-size:11px; margin-bottom:20px; padding-bottom:10px; } a{ color:#0099FF; font-weight:bold; } /* Box Style */ .success, .warning, .errormsgbox, .validation { border: 1px solid; margin: 0 auto; padding:10px 5px 10px 60px; background-repeat: no-repeat; background-position: 10px center; font-weight:bold; width:450px; } .success { color: #4F8A10; background-color: #DFF2BF; background-image:url('images/success.png'); } .warning { color: #9F6000; background-color: #FEEFB3; background-image: url('images/warning.png'); } .errormsgbox { color: #D8000C; background-color: #FFBABA; background-image: url('images/error.png'); } .validation { color: #D63301; background-color: #FFCCBA; background-image: url('images/error.png'); } </style> </head> <body> <form action="login.php" method="post" class="registration_form"> <fieldset> <legend>Login Form </legend> <p>Enter Your username and Password Below </p> <div class="elements"> <label for="name">Email :</label> <input type="text" id="e-mail" name="e-mail" size="25" /> </div> <div class="elements"> <label for="Password">Password:</label> <input type="password" id="Password" name="Password" size="25" /> </div> <div class="submit"> <input type="hidden" name="formsubmitted" value="TRUE" /> <input type="submit" value="Login" /> </div> </fieldset> </form> Go Back to <a href="#">Account Verification on sign up</a> </body> </html> This is the page's code where user is redirected after login Code: [Select] <?php ob_start(); session_start(); if(!isset($_SESSION['Username'])){ header("Location: login.php"); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Member Area </title> <style type="text/css"> .success { border: 1px solid; margin: 0 auto; padding:10px 5px 10px 60px; background-repeat: no-repeat; background-position: 10px center; font-weight:bold; width:450px; color: #4F8A10; background-color: #DFF2BF; background-image:url('images/success.png'); } </style> </head> <body> <div class="success">Welcome , <?php echo $_SESSION['Username'] ; ?></div> <? $b = time (); $date1 =date( "Y-m-d;h:i:s" , mktime(date("h")+6, date("i"), date("s"), date("m") , date("d"), date("Y"))); $str_time = "&receivedtimestamp="; $str_msg = "&msg=bkt"; $str_from = "from="; ?> <a href="http://testext.i-movo.com/api/receivesms.aspx?<?echo $str_from;?><?echo $_SESSION['phone'];?><?echo $str_time;?><?echo $date1;?><?echo $str_msg;?>">Get a Cupon</a> </br> <?php echo $_SESSION['Email'] ; ?> </br> <?php echo $_SESSION['phone'] ; ?> <p><strong>My Account</strong></p> <a href="myaccount.php">My Account</a><br> <a href="mysettings.php">Settings</a><br> <a href="logout.php">Logout </a> </body> </html> And finally the database structure is this one ... Code: [Select] CREATE TABLE IF NOT EXISTS `members` ( `Memberid` int(10) NOT NULL AUTO_INCREMENT, `Username` varchar(20) NOT NULL, `Email` varchar(50) NOT NULL, `Password` varchar(10) NOT NULL, `phone` varchar(25) NOT NULL, `Activation` varchar(60) DEFAULT NULL, PRIMARY KEY (`Memberid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ; Please help me with this because i'm going mad I want to show data for logged in user, i am using sessions to login. This is the code i already have: // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); //this selects everything for the current user, ready to be used in the script below $result = mysql_query("SELECT id, points, ingame_points, ingame_money, ingame_items FROM members; WHERE username = $_SESSION['myusername']"); //this function will take the above query and create an array while($row = mysql_fetch_array($result)) { //with the array created above, I can create variables (left) with the outputted array (right) $points = $row['points']; $id = $row['id']; $ingame_points = $row['ingame_points']; $ingame_money = $row['ingame_money']; $ingame_items = $row['ingame_items']; } Help ? I have a problem which I've been trying to fix for a while now with htmlentities. I've written my own small cms which is available for the public, and recently I recieved a report that it's vulnerable to an XSS attack: http://host/editText.php?fieldname=slogan&content=slogan<img src=x onerror=alert("XSS")> This vulnerability only works if the user is logged in. I want to secure it anyway to give the security companies contacting me about this a break. I've been rolling around the internet trying to find a simple answer how to prevent this XSS attack with HTMLENTITIES. I've even tried writing my own solutions with the htmlentities and it doesn't seem to solve the problem/stop the attack. I'm thinking something like htmlEntities($content); //but again, this won't do the job. Here's the editText.php Code: [Select] <?php session_start(); function getSlug( $page ) { $page = strip_tags( $page ); preg_match_all( "/([a-z0-9A-Z-_]+)/", $page, $matches ); $matches = array_map( "ucfirst", $matches[0] ); $slug = implode( "-", $matches ); return $slug; } $fieldname = $_REQUEST['fieldname']; $encrypt_pass = @file_get_contents("files/password"); if ($_COOKIE['wondercms']!=$encrypt_pass) { echo "You must login before using this function!"; exit; } $content = rtrim(stripslashes($_REQUEST['content'])); // if to only allow specified tags if($fieldname=="title") $content = strip_tags($content); else $content = strip_tags($content,"<audio><source><embed><iframe><p><h1><h2><h3><h4><h5><h6><a><img><u><i><em><strong><b><strike><center><pre>"); $content = trim($content); $content = nl2br($content); if(!$content) $content = "Please be sure to enter some content before saving. Just type anything in here."; $content = preg_replace ("/%u(....)/e", "conv('\\1')", $content); if($fieldname>0 && $fieldname<4) $fname = "attachment$fieldname"; else $fname = $fieldname; $file = @fopen("files/$fname.txt", "w"); if(!$file) { echo "<h2 style='color:red'>*** ERROR *** unable to open content_$fieldname</h2><h3>But don't panic!</h3>". "Please set the correct read/write permissions to the files folder.<br/> Find the /files/ folder and CHMOD it to 751.<br /><br /> If this still gives you problems, open up the /files/ folder, select all files and CHMOD them to 640.<br /><br /> If this doesn't work, contact me <a href='http://krneky.com/en/contact'>right here</a>."; exit; } fwrite($file, $content); fclose($file); echo $content; // convert udf-8 hexadecimal to decimal function conv($hex) { $dec = hexdec($hex); return "&#$dec;"; } ?> There are only 3 files altogether, if someone needs index I'll post that too. Hi Guys, Just a quick introduction I am NOT a student I am a IT Technician in a School in the South of the United Kingdom. I am trying to write a PHP Script with a Function that Checks if the user is logged in, if the user is logged in then it shows the user the content on the page but if they are not logged in then to show a blank page with a link to the Login Page. I need it to be simple. I just want it to check if a useer is logged in but if there not only show some content on a page. Can anyone help? My Users login into a php Session. Thanks for any help you can offer. Best Regards Thomas This will be a little difficult to explain, but keep with me. On the profile.php page. It starts a new session. Code: [Select] // Connect to MySQL... $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed"); mysql_select_db($database, $conn) or die("Selecting MySQL database failed"); // Run our query, see if session username exists in session field... $sql="select username,email from user where username='{$_SESSION['user']}' limit 1"; $result=mysql_query($sql,$conn); // Parse our results into $data (as an associative array)... $data=mysql_fetch_assoc($result); // If one row was found in the result set, username exists... if (mysql_num_rows($result)==1) { $_SESSION['sellername'] = $data['username']; So what I am hoping that is doing, is the session named "sellername" is stored with the variable of the logged in user. In this example "testuser". Now the page updates.php will have an id attached to like so: updates.php?id=13. Which will have info only available for testuser's eyes. On the page it does this. Code: [Select] // Connect to MySQL... $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed"); mysql_select_db($database, $conn) or die("Selecting MySQL database failed"); // Run our query, see if session username exists in session field... $sql="select username from user where username='{$_SESSION['user']}' limit 1"; $result=mysql_query($sql,$conn); // Parse our results into $data (as an associative array)... $data=mysql_fetch_assoc($result); // If one row was found in the result set, username exists... if (mysql_num_rows($result)==1) { $query='select seller from listings where seller = "'.$data['username'].'"'; $queryresult=mysql_query($query,$conn); while($info = mysql_fetch_assoc($queryresult)){ if ( $_SESSION['sellername'] == $info['seller'] ){ The if statement should process: "If the session variable for 'sellername' equals the database entry 'seller' then display the rest of the page." However, no matter what user is logged, it will display the page. Any ideas? on all my secured pages at the the very top the code is Code: [Select] <?php require ("u_check_login.php"); ?> and then the u_check_login.php code is Code: [Select] <?php require('database.php'); //Include DB connection information $ip = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]); //Get user's IP Address $email = mysql_real_escape_string($_COOKIE['uemail']); //Get username stored in cookie $pp = mysql_real_escape_string($_COOKIE['pp']); if ($pp == 1){ $sessionid = mysql_real_escape_string($_COOKIE['sessionid']); //Get user's session ID $check = mysql_query("SELECT * FROM `users` WHERE `email` = '$email' AND `session_id` = '$sessionid' AND `login_ip` = '$ip' AND `pp` = '1' ") or die(mysql_error()); //Check if all information provided from the user is valid by checking in the DB $answer = mysql_num_rows($check); //Return number of results found. Equal to 0 if not logged in or 1 if logged in. if ($answer == 0 || $sessionid == '') { //Check if login is valid. If not redirect user to login page header('Location: ulogin.php'); exit(); } $row = mysql_fetch_array($check); $email = stripslashes($row['email']); }else{ header('Location: ulogin.php'); } ?> and this error is being displayed on my page that is supposed to not have let me on because i was not logged in Code: [Select] Warning: Cannot modify header information - headers already sent by (output started at /home/content/03/8587103/html/pinkpanthers/pinkpanthers.php:1) in /home/content/03/8587103/html/pinkpanthers/u_check_login.php on line 17 I have members.php: <?php /********************************************************************** Filename: members.php Version: $Id: members.php 17 2007-04-09 09:40:35Z Jez $ Description: This file displays the members screen once they've logged in. **********************************************************************/ /* Members script: */ include_once("config.php"); // Check user logged in already: checkLoggedIn("yes"); doCSS(); print("Welcome to the members page <b>".$_SESSION["login"]."</b><br>\n"); print("Your password is: <b>".$_SESSION["password"]."</b><br>\n"); print("<a href=\"logout.php"."\">Logout</a>"); ?> and functions.php: <?php /********************************************************************** Filename: functions.php Description: This file contains main stock of functions. This file is automatically 'include()'d by every page that include()'s the file 'config.php'. This has the benefit that every page that includes 'config.php' will have access to all of the functions in this file. **********************************************************************/ /******************************************************\ * Function Name : connectToDB() * * Task : create connection to db * * Arguments : none * * Globals: all defined in config.php * * Returns : none, sets $link * \******************************************************/ function connectToDB() { global $link, $dbhost, $dbuser, $dbpass, $dbname; /* Database connection: The PHP function mysql_pconnect() connects to a MySQL database with the arguments it is given. mysql_pconnect() creates a persistent database connection which can save some time when a number of mysql connections are made to the same db with the same user/password/dbhost triple. Further, when the execution of the PHP script ends, the connection to the database is NOT closed. In some rare cases this can cause problems. Alternatively mysql_connect() can be used and takes the same arguments as mysql_pconnect(). However mysql_connect() does not maintain a persistent connection - every call to mysql_connect() creates a new db connection. On a busy server this can significantly increase the amount of time taken to execute queries on the db. */ ($link = mysql_pconnect("$dbhost", "$dbuser", "$dbpass")) || die("Couldn't connect to MySQL"); // select db: mysql_select_db("$dbname", $link) || die("Couldn't open db: $dbname. Error if any was: ".mysql_error() ); } // end func dbConnect(); /******************************************************\ * Function Name : newUser($login, $pass) * * Task : Create a new user entry in the users table based on args passed * * Arguments : string($login, $pass) * * Returns : int($id), $id of new user * \******************************************************/ function newUser($login, $password) { /* Creating a New User Record in the DB: In this function we create a new user record in the db. We first build a query and save it into the $query variable. The query statement says: 'Insert the value of $login and $password into the 'login' and 'password' columns in the 'users' table' */ global $link; $query="INSERT INTO users (login, password) VALUES('$login', '$password')"; $result=mysql_query($query, $link) or die("Died inserting login info into db. Error returned if any: ".mysql_error()); return true; } // end func newUser($login, $pass) /******************************************************\ * Function Name : displayErrors($messages) * * Task : display a list of errors * * Arguments : array $messages * * Returns : none * \******************************************************/ function displayErrors($messages) { /* Error Handling functions: An error handling function is useful to have in any project. This particular function takes an array of messages, and for each message displays it in a list using HTML <ul><li></li></ul> tags. */ print("<b>There were problems with the previous action. Following is a list of the error messages generated:</b>\n<ul>\n"); foreach($messages as $msg){ print("<li>$msg</li>\n"); } print("</ul>\n"); } // end func displayErrors($messages) /******************************************************\ * Function Name : checkLoggedIn($status) * * Task : check if a user is (isn't) logged in depending on $status * * Arguments : quasi(!) boolean $status - "yes" or "no" * * Returns : * \******************************************************/ function checkLoggedIn($status){ /* Function to check whether a user is logged in or not: This is a function that checks if a user is already logged in or not, depending on the value of $status which is passed in as an argument. If $status is 'yes', we check if the user is already logged in; If $status is 'no', we check if the user is NOT already logged in. */ switch($status){ // if yes, check user is logged in: // ie for actions where, yes, user must be logged in(!) case "yes": if(!isset($_SESSION["loggedIn"])){ header("Location: login.php"); exit; } break; // if no, check NOT logged in: // ie for actions where user can't already be logged in // (ie for joining up or logging in) case "no": /* The '===' operator differs slightly from the '==' equality operator. $a === $b if and only if $a is equal to $b AND $a is the same variable type as $b. for example, if: $a="2"; <-- $a is a string here $b=2; <-- $b is an integer here then this test returns false: if($a===$b) whereas this test returns true: if($a==$b) */ if(isset($_SESSION["loggedIn"]) && $_SESSION["loggedIn"] === true ){ header("Location: members.php"); } break; } // if got here, all ok, return true: return true; } // end func checkLoggedIn($status) /******************************************************\ * Function Name : checkPass($login, $password) * * Task : check login/passwd match that stored in db * * Arguments : string($login, $password); * * Returns : array $row - array of member details on success * false on failure \******************************************************/ function checkPass($login, $password) { /* Password checking function: This is a simple function that takes the $login name and $password that a user submits in a form and checks that a row exists in the database whe the value of the 'login' column is the same as the value in $login and the value of the 'password' column is the same as the value in $password If exactly one row is returned, then that row of data is returned. If no row is found, the function returns 'false'. */ global $link; $query="SELECT login, password FROM users WHERE login='$login' and password='$password'"; $result=mysql_query($query, $link) or die("checkPass fatal error: ".mysql_error()); // Check exactly one row is found: if(mysql_num_rows($result)==1) { $row=mysql_fetch_array($result); return $row; } //Bad Login: return false; } // end func checkPass($login, $password) /******************************************************\ * Function Name : cleanMemberSession($login, $pass) * * Task : populate a session variable * * Arguments : string $login, string $pass taken from users table in db. * * Returns : none * \******************************************************/ function cleanMemberSession($login, $password) { /* Member session initialization function: This function initializes 3 session variables: $login, $password and $loggedIn. $login and $password are used on member pages (where you could allow the user to change their password for example). $loggedIn is a simple boolean variable which indicates whether or not the user is currently logged in. */ $_SESSION["login"]=$login; $_SESSION["password"]=$password; $_SESSION["loggedIn"]=true; } // end func cleanMemberSession($login, $pass) /******************************************************\ * Function Name : flushMemberSession($session) * * Task : unset session variables and destroy session * * Arguments : array $session * * Returns : true * \******************************************************/ function flushMemberSession() { /* Member session destruction function: This function unsets all the session variables initialized above and then destroys the current session. */ // use unset to destroy the session variables unset($_SESSION["login"]); unset($_SESSION["password"]); unset($_SESSION["loggedIn"]); // and use session_destroy to destroy all data associated // with current session: session_destroy(); return true; } // send func flushMemberSession() /******************************************************\ * Function Name : doCSS() * * Task : output the CSS for the screens * * Arguments : * * Returns : * \******************************************************/ function doCSS() { /* CSS Output: This function simply outputs some cascading style sheet data for markup by the user's browser. */ ?> <style type="text/css"> body{font-family: Arial, Helvetica; font-size: 10pt} h1{font-size: 12pt} </style> <?php } // end func doCSS() # function validates HTML form field data passed to it: function field_validator($field_descr, $field_data, $field_type, $min_length="", $max_length="", $field_required=1) { /* Field validator: This is a handy function for validating the data passed to us from a user's <form> fields. Using this function we can check a certain type of data was passed to us (email, digit, number, etc) and that the data was of a certain length. */ # array for storing error messages global $messages; # first, if no data and field is not required, just return now: if(!$field_data && !$field_required){ return; } # initialize a flag variable - used to flag whether data is valid or not $field_ok=false; # this is the regexp for email validation: $email_regexp="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|"; $email_regexp.="(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; # a hash array of "types of data" pointing to "regexps" used to validate the data: $data_types=array( "email"=>$email_regexp, "digit"=>"^[0-9]$", "number"=>"^[0-9]+$", "alpha"=>"^[a-zA-Z]+$", "alpha_space"=>"^[a-zA-Z ]+$", "alphanumeric"=>"^[a-zA-Z0-9]+$", "alphanumeric_space"=>"^[a-zA-Z0-9 ]+$", "string"=>"" ); # check for required fields if ($field_required && empty($field_data)) { $messages[] = "$field_descr is a required field."; return; } # if field type is a string, no need to check regexp: if ($field_type == "string") { $field_ok = true; } else { # Check the field data against the regexp pattern: $field_ok = ereg($data_types[$field_type], $field_data); } # if field data is bad, add message: if (!$field_ok) { $messages[] = "Please enter a valid $field_descr."; return; } # field data min length checking: if ($field_ok && ($min_length > 0)) { if (strlen($field_data) < $min_length) { $messages[] = "$field_descr is invalid, it should be at least $min_length character(s)."; return; } } # field data max length checking: if ($field_ok && ($max_length > 0)) { if (strlen($field_data) > $max_length) { $messages[] = "$field_descr is invalid, it should be less than $max_length characters."; return; } } } ?> The db has an table users with id, login, password, site Question how can i get inf from "site" raw for logged user on members.php ( as a link). Pls help thanks I would like my website to show which users are logged in. Is there a simple way of retrieving all session ids from the server that have been allocated and are active in order to do this? I know this could lead to faulty information, but would appear to be the simplest and reliable. Thanks. Hi - how's it going? I've been working on something with no luck and I'm wondering if you have any ideas. I have two tables; Members and Events. When a member logs in they are redirected to a page where I want them to be able to see a list of events that they have created based on a user ID that is common in both tables. So if the member has a memberID of 123 I want them to see any events that have the userID of 123. I used two different column names just for clarity. I've tried a number of variations on the following code: <?php session_start(); header("Cache-control: private"); // Connect to Database include ('includes/db.php'); //Has login info // If not logged in if (!$_SESSION['pkMemberID']) { echo ("<div class='box'><h2>Sorry, you are not logged in!</h2>"); exit(); } // Convert Session variable 'pkMemberID' to simple variable. $memberID = $_SESSION['memberID']; $pkMemberID = $_SESSION['pkMemberID']; $name = $_SESSION['name']; //Query Events $sql = "SELECT * FROM events WHERE userID = $memberID"; $result = mysql_query($sql); $num_rows = mysql_num_rows($result); echo ("<div>Events:<br />"); // Event exists if (!($num_rows == 0)) { $myrow = mysql_fetch_array($result); do { printf ('<span>– <a href="event_edit.php?pkEventID=%s">%s</a></span><br />', $myrow['pkEventID'], $myrow['eventName']); } while ($myrow = mysql_fetch_array($result)); } echo ("</div>"); //End Events //end page ?> Sometimes I get errors, sometimes just nothing. Any advice would be appreciated. I have two tables. Table Name:Users Fields: User_name user_email user_level pwd 2.Reference Fields: refid username origin destination user_name in the users table and the username field in reference fields are common fields. There is user order form.whenever an user places an order, refid field in reference table will be updated.So the user will be provided with an refid Steps: 1.User needs to log in with a valid user id and pwd 2.Once logged in, there will be search, where the user will input the refid which has been provided to him during the time of order placement. 3.Now User is able to view all the details for any refid 3.Up to this we have completed. Query: Now we need to retrieve the details based on the user logged in. For eg: user 'USER A' has been provided with the referenceid '1234' during the time of order placement user 'USER B' has been provided with the referenceid '2468' during the time of order placement When the userA login and enter the refid as '2468' he should not get any details.He should get details only for the reference ids which is assigned to him. Hi, All: I'm trying to figure out what way it's the best way to pull info belonging to a specific user based on whether he's a logged-in "member", and want to make sure he's not able to access any other member's details... would the best way be to try to match the user's "username" stored in a $_SESSION when fetching his info, something like this: Code: [Select] <?php // Assume the login combo is this: $username = $_POST['username']; $password = $_POST['password']; // Assume he has already logged in: $_SESSION['username'] = $username; //EXAMPLE 1: SELECTING user info simply from actual DB username/password match: if ($_SESSION['username']) { $userRecords = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'"); $userInfo = mysql_fetch_array($userRecords); echo $userInfo['id'] . $userInfo['username'] . $userInfo['first-name'] . $userInfo['last-name'] . $userInfo['date-register']; } // EXAMPLE 2: or SELECTING user info based on $_SESSION['username'] value: if ($_SESSION['username']) { $userRecords = mysql_query("SELECT * FROM users WHERE username = . $_SESSION['username'] . AND password = '$password'"); $userInfo = mysql_fetch_array($userRecords); echo $userInfo['id'] . $userInfo['username'] . $userInfo['first-name'] . $userInfo['last-name'] . $userInfo['date-register']; } ?> So, my question is, are this actually working differently? is one better than the other as far as security, preventing other users from hacking either on purpose or accidenally into other user's details? thank! Appreciate any feedback... |